Instructions on How to Use the Cocoon Gem in Rails 6

Instructions on How to Use the Cocoon Gem in Rails 6

When it comes to the ROR framework, there are an infinite number of gems available. It is one of those diamonds that is Cocoon. If you haven't done much research on the Cocoon Gem, then you shouldn't be concerned about it! In this detailed tutorial, we will learn more about the Cocoon gem and then put it into practice by implementing an example. For this reason, get ready to integrate cocoon gem and start coding!

Introduction

Through the use of the cocoon gem in Ruby on Rails, we will acquire the knowledge necessary to develop a rails form that is both complicated and dynamic.

Let's say you want to get your users to fill out a form in which they can enter the names of their contacts. The amount of contacts?that your user will have is not something that you know in advance; therefore, how can you add a certain number of fields to the layout?

In order to provide a solution to this query, Rails does not have any built-in support. The use of cocoon gem is therefore an option for resolving this issue. Through the use of JavaScript, Cocoon is able to power nested forms, which enables fields to be dynamically added or removed.

With the help of this cocoon gem example, we will learn how to use cocoon gem to add or remove nested fields in an asynchronous manner without having to generate a new request. A demo will be developed in which users will be able to add an unlimited number of contacts. Therefore, the name of the contact?will be an attribute that is nested within the name of the?user.

Rails 6: Instructions on How to Implement the Cocoon Gem

Make a new application for rails

rails new my-cocoon-gem-app        

The following command should be used to add jQuery to the project at this point:

yarn add jquery        

Update the config/webpack/environment.js file

const { environment } = require('@rails/webpacker')
 
const webpack = require('webpack')
environment.plugins.prepend('Provide',
   new webpack.ProvidePlugin({
       $: 'jquery/src/jquery',
       jQuery: 'jquery/src/jquery'
   })
)
 
module.exports = environment        

Add the cocoon gem to the Gemfile

gem 'cocoon'        

The cocoon gem should be added and installed using the bundle.

When the cocoon gem is included to the bundle and installed using the bundle, the cocoon gem will not be installed completely for the application. In addition to that, we need to include the companion package for the cocoon that is made out of yarn.

yarn add github:nathanvda/cocoon        

Add app/javascript/packs/application.js file.

require('jquery')
import "cocoon";        

In order to install the cocoon gem, run this command.

bundle install        

Let's generate the required models

rails g model User
rails g model Contact        

Edit the migration files

Proceed to edit the migration files that were produced when the two commands mentioned above were being executed. The name of the file will be something along the lines of 20240127114709_create_users.rb and 20240127114810_create_contacts.rb, and it will be located within the db directory.

class CreateUsers < ActiveRecord::Migration[6.1]
 def change
   create_table :users do |t|
     t.string :name, null: false
     t.timestamps
   end
 end
end        
class CreateContacts < ActiveRecord::Migration[6.1]
 def change
   create_table :contacts do |t|
     t.references :user, null: false, foreign_key: true
     t.string :contact_name, null: false
     t.timestamps
   end
 end
end        

Now let's migrate the database by command

rails db:migrate        

Update models to setup associations

class User < ApplicationRecord
 has_many :contacts, dependent: :destroy
 accepts_nested_attributes_for :contacts
end        
class Contact < ApplicationRecord
 belongs_to :user
end        

Creating users controller

The following code should be written into the app/controllers/users_controller.rb file. You can see that we have included the _destroy virtual attribute within the permissible parameters for the user. This is something that we have done here. The purpose of this is to eliminate the nested fields by using the delete button that is provided.

class UsersController < ApplicationController
 def new
   @user = User.new
   @contacts = @user.contacts.build
 end
 
 def create
   @user = User.new(user_params)
   if @user.save
     redirect_to user_path(@user)
   else
     render action: :new
   end
 end
 
 def show
   @user = User.find(params[:id])
   @contacts = @user.contacts
 end
 
 private
 
 def user_params
   params.require(:user).permit(:name, contacts_attributes: [:id, :contact_name, :_destroy])
 end
end        

Creating new user form view file

We are now on our way to the user interface. To add the following code, you will need to create a new file called new.html.erb and place it under the app/views/users directory. A helpful function called link_to_add_association, which is supplied by the cocoon gem, has been utilized by us. With the help of this function, a link will be added, and we will be able to utilize it to dynamically add a new field.

<%= form_for(@user) do |f| %>
  <br>
  <br>
  <div>
    <div>
      <%= f.label :name %>
      <%= f.text_field :name %>
    </div>

    <div>
      <%= f.fields_for :contacts do |t| %>
        <%= render "contact_fields", :f => t %>
      <% end %>
      
      <div>
        <br>
        <%= link_to_add_association "Add Contact", f, :contacts %>
      </div>
    </div>
    
    <div>
      <br>
      <%= f.submit %>
    </div>
  </div>
<% end %>        

Create contacts fields partial in the same directory

The same thing should be done with another file called _contact_fields.html.erb, which should be created in the same directory as new.html.erb, and the following code should be added to it. For the purpose of removing a field from the layout in a dynamic manner, we have implemented an additional utility function called link_to_remove_association, which is given by the cocoon gem.

<div class="nested-fields">
   <%= f.label "Contact's name" %>
   <%= f.text_field :contact_name %>
  
   <%= link_to_remove_association "Delete", f %>
</div>        

Setup routes in file the config/routes.rb file

Rails.application.routes.draw do
 root 'users#new'
 
 resources :users
end        

Create a show.html.erb file

Create a show.html.erb file in the app/views/users directory and update it with the below-mentioned code

<h4><%= @user.name %>'s Contacts</h4>
 
<% @contacts.each do |contact| %>
 <li><%= contact.contact_name %></li>
<% end %>        

Conclusion

Consequently, this was about the instance of how to implement the cocoon gem. Hopefully, the tutorial has been helpful to you in the way that you desired. If you are a fan of Ruby on Rails and are interested in learning more about the operating system, then you should go to ROR tutorials and begin exploring!


You can hire Plural Code Technologies, the best ROR development company, to develop a top-notch quality app solution as per your requirements. Our experienced ROR developers take care of coming up with unmatched quality-driven solutions that are built to perform the best and serve your end-users right. Contact us using the email particulars provided on the website.


要查看或添加评论,请登录

Nishant Goyal的更多文章

社区洞察