{"id":18383,"date":"2021-05-24T07:02:41","date_gmt":"2021-05-24T07:02:41","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=18383"},"modified":"2024-11-13T07:37:01","modified_gmt":"2024-11-13T07:37:01","slug":"cocoon-gem-example-in-rails-6","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/cocoon-gem-example-in-rails-6","title":{"rendered":"Cocoon Gem Example: How to Implement Cocoon Gem in Rails 6?"},"content":{"rendered":"<p><strong>There are innumerable gems available for the ROR framework. Cocoon is one of those gems. If you haven\u2019t explored much about the <a href=\"https:\/\/github.com\/nathanvda\/cocoon\" target=\"_blank\" rel=\"noopener\">Cocoon Gem<\/a>, then don\u2019t worry! In this step-by-step guide, we will implement Cocoon gem example and learn more about it. So, get ready to code and integrate cocoon gem!<\/strong><\/p>\n<h2>Introduction<\/h2>\n<p>In this tutorial, we learn how to create complex and dynamic rails form using the cocoon gem in Ruby on Rails. <\/p>\n<p>Suppose you want to create a form in which you want your users to enter their friends\u2019 names. You do not know in advance how many friends your user will have, so how to add a specific number of fields in the layout? <\/p>\n<p>Rails do not have any built-in support to answer this question. Thus, to resolve this issue, we can use <em>cocoon gem<\/em>. Cocoon powers nested forms with JavaScript, allowing fields to be added or removed dynamically. <\/p>\n<p>In this cocoon gem example, we will see how to use cocoon gem to add or remove nested fields asynchronously without generating a new request. We will develop a demo where users can add <em>n<\/em> number of friends. So, the friend&#8217;s name will be a nested attribute of the user&#8217;s name.<\/p>\n<p>Quick Read:- <a href=\"https:\/\/www.bacancytechnology.com\/blog\/ruby-on-rails-gems\" target=\"_blank\" rel=\"noopener\">55 RoR Gems: Pin To Plane For Developing RoR Application<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Cocoon-gem.jpg\" alt=\"cocoon gem\" width=\"1100\" height=\"944\" class=\"aligncenter size-full wp-image-18408\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Cocoon-gem.jpg 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Cocoon-gem-300x257.jpg 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Cocoon-gem-1024x879.jpg 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Cocoon-gem-768x659.jpg 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<h2>Goal of Cocoon Gem Tutorial<\/h2>\n<p>Before starting with our Cocoon gem example, let\u2019s see the video of the nested form which we will implement.<\/p>\n<p><iframe loading=\"lazy\" width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/ZDj7fFE5Ei8\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/p>\n<h2>Cocoon Gem Example: Steps to Implement Cocoon Gem in Rails 6.<\/h2>\n<p>Let\u2019s understand how to use cocoon gem in Rails 6 step by step guide to implement Cocoon Gem in your Ruby on Rails project.<\/p>\n<h3>1. Create a new rails app<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-a-new-rails-app.png\" alt=\"Create a new rails app\" width=\"1342\" height=\"628\" class=\"aligncenter size-full wp-image-21999\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-a-new-rails-app.png 1342w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-a-new-rails-app-300x140.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-a-new-rails-app-1024x479.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-a-new-rails-app-768x359.png 768w\" sizes=\"auto, (max-width: 1342px) 100vw, 1342px\" \/><\/p>\n<h3>2. Now, add jquery to the project using the following command:<\/h3>\n<pre>yarn add jquery<\/pre>\n<h3>3. Update the config\/webpack\/environment.js file<\/h3>\n<p>Update the config\/webpack\/environment.js file with the following code<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Update-the-file-.png\" alt=\"Update the file\" width=\"1177\" height=\"520\" class=\"aligncenter size-full wp-image-22000\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Update-the-file-.png 1177w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Update-the-file--300x133.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Update-the-file--1024x452.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Update-the-file--768x339.png 768w\" sizes=\"auto, (max-width: 1177px) 100vw, 1177px\" \/><\/p>\n<h3>4. Add the cocoon gem to the Gemfile<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Add-the-cocoon-gem.png\" alt=\"Add the cocoon gem\" width=\"1469\" height=\"363\" class=\"aligncenter size-full wp-image-22001\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Add-the-cocoon-gem.png 1469w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Add-the-cocoon-gem-300x74.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Add-the-cocoon-gem-1024x253.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Add-the-cocoon-gem-768x190.png 768w\" sizes=\"auto, (max-width: 1469px) 100vw, 1469px\" \/><\/p>\n<\/h3>\n<p>5. Add and install the cocoon gem using bundle<\/h3>\n<p>Adding and installing the cocoon gem using the bundle will not completely install the cocoon gem for the app. For that, we also need to add the companion package for cocoon using yarn.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/installing-the-cocoon-gem.png\" alt=\"installing the cocoon gem\" width=\"1280\" height=\"494\" class=\"aligncenter size-full wp-image-22002\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/installing-the-cocoon-gem.png 1280w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/installing-the-cocoon-gem-300x116.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/installing-the-cocoon-gem-1024x395.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/installing-the-cocoon-gem-768x296.png 768w\" sizes=\"auto, (max-width: 1280px) 100vw, 1280px\" \/><\/p>\n<h3>6. Add app\/javascriptspacks\/application.js file.<\/h3>\n<p>Add the following two lines in the app\/javascript\/packs\/application.js file.<br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/cocoon-gem.png\" alt=\"cocoon gem\" width=\"1232\" height=\"563\" class=\"aligncenter size-full wp-image-22003\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/cocoon-gem.png 1232w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/cocoon-gem-300x137.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/cocoon-gem-1024x468.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/cocoon-gem-768x351.png 768w\" sizes=\"auto, (max-width: 1232px) 100vw, 1232px\" \/><\/p>\n<h3>7. Run this command to install cocoon gem<\/h3>\n<pre>bundle install<\/pre>\n<h3>8. Generate User model<\/h3>\n<p>Now generate a User model<\/p>\n<pre>rails g model User<\/pre>\n<h3>9. Generate Friend model<\/h3>\n<p>Generate Friend model with the help of the following command:<\/p>\n<pre>rails g model Friend<\/pre>\n<h3>10. Edit the migration files<\/h3>\n<p>Now, edit the migration files generated while executing the above two commands. The file name will be like 20210427114709_create_users.rb and 20210427114810_create_friends.rb present inside the db\/migrate directory.<\/p>\n<p><strong> db\/migrate\/20210427114709_create_users.rb<\/strong><\/p>\n<pre>class CreateUsers < ActiveRecord::Migration[6.1]\r\n def change\r\n   create_table :users do |t|\r\n     t.string :name, null: false\r\n     t.timestamps\r\n   end\r\n end\r\nend<\/pre>\n<p><strong>db\/migrate\/20210427114810_create_friends.rb<\/strong><\/p>\n<pre>class CreateFriends < ActiveRecord::Migration[6.1]\r\n def change\r\n   create_table :friends do |t|\r\n     t.references :user, null: false, foreign_key: true\r\n     t.string :friend_name, null: false\r\n     t.timestamps\r\n   end\r\n end\r\nend<\/pre>\n<h3>Save the above file<\/h3>\n<p>Now, save the above file after making changes; it\u2019s time to migrate to reflect the above changes in the application\u2019s schema. <\/p>\n<pre>$ rails db:migrate<\/pre>\n<h3>12. Update the model file<\/h3>\n<p>Now, update the model file of User, i.e., app\/models\/user.rb <\/p>\n<pre>class User < ApplicationRecord\r\n has_many :friends, dependent: :destroy\r\n accepts_nested_attributes_for :friends\r\nend<\/pre>\n<h3>13. Same like above, we need to make changes in the model file of Friend, i.e., app\/models\/friend.rb<\/h3>\n<pre>class Friend < ApplicationRecord\r\n belongs_to :user\r\nend<\/pre>\n<h3>14. Generate User controller<\/h3>\n<pre>rails g controller users<\/pre>\n<h3>15. Open app\/controllers\/users_controller.rb<\/h3>\n<p>Open app\/controllers\/users_controller.rb and write the below-mentioned code. Here, as you can see, we have added the _destroy virtual attribute inside the permitted parameters for the user. The reason is to destroy the nested fields (with the delete button).<\/p>\n<pre>class UsersController < ApplicationController\r\n def new\r\n   @user = User.new\r\n   @friends = @user.friends.build\r\n end\r\n \r\n def create\r\n   @user = User.new(user_params)\r\n   if @user.save\r\n     redirect_to user_path(@user)\r\n   else\r\n     render action: :new\r\n   end\r\n end\r\n \r\n def show\r\n   @user = User.find(params[:id])\r\n   @friends = @user.friends\r\n end\r\n \r\n private\r\n \r\n def user_params\r\n   params.require(:user).permit(:name, friends_attributes: [:id, :friend_name, :_destroy])\r\n end\r\nend<\/pre>\n<h3>16. Create a new file<\/h3>\n<p>Moving towards the UI part now. Create a new file - new.html.erb inside app\/views\/users directory and add the following code. We have used a helper function link_to_add_association provided by the cocoon gem. This function will add a link so that we can use it to add a new field dynamically.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-new-file.png\" alt=\"Create new file\" width=\"1162\" height=\"807\" class=\"aligncenter size-full wp-image-22004\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-new-file.png 1162w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-new-file-300x208.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-new-file-1024x711.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/Create-new-file-768x533.png 768w\" sizes=\"auto, (max-width: 1162px) 100vw, 1162px\" \/><\/p>\n<\/h3>\n<p>17. Create another file in the same directory<\/h3>\n<p>Similarly, create another file in the same directory as of new.html.erb with the name  _friend_fields.html.erb and add the following code. We have implemented another helper function link_to_remove_association provided by the cocoon gem to delete a field dynamically from the layout.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/create-another-file.png\" alt=\"create another file\" width=\"1128\" height=\"517\" class=\"aligncenter size-full wp-image-22005\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/create-another-file.png 1128w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/create-another-file-300x138.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/create-another-file-1024x469.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2021\/05\/create-another-file-768x352.png 768w\" sizes=\"auto, (max-width: 1128px) 100vw, 1128px\" \/><\/p>\n<h3>18. Update the config\/routes.rb file<\/h3>\n<p>Now, it's time to update the config\/routes.rb file with the following code<\/p>\n<pre>Rails.application.routes.draw do\r\n root 'users#new'\r\n \r\n resources :users\r\n \r\n # For details on the DSL available within this file, see https:\/\/guides.rubyonrails.org\/routing.html\r\nend<\/pre>\n<h3>19. Create a show.html.erb file<\/h3>\n<p>Create a show.html.erb file in the app\/views\/users directory and update it with the below-mentioned code<\/p>\n<pre><h4><%= @user.name %>'s Friends<\/h4>\r\n \r\n<% @friends.each do |friend| %>\r\n <li><%= friend.friend_name %><\/li>\r\n<% end %><\/pre>\n<p>Here\u2019s the entire source code for the cocoon gem example - <strong><a href=\"https:\/\/github.com\/kishan-aghera\/cocoon-gem-example\" target=\"_blank\" rel=\"noopener\">Github Repository<\/a><\/strong><\/p>\n<p><strong>You May Also Like to Read: <\/strong>How to Download and <a href=\"https:\/\/www.bacancytechnology.com\/blog\/install-ruby-gems\" target=\"_blank\" rel=\"noopener\">Install Ruby Gems<\/a> into Gemfile<\/p>\n<h2>Conclusion<\/h2>\n<p>So, this was about how to implement cocoon gem example. I hope the tutorial has helped you the way you wanted. If you\u2019re a ROR enthusiast and want to learn more about Ruby on Rails then visit <a href=\"https:\/\/www.bacancytechnology.com\/tutorials\/ruby-on-rails\" target=\"_blank\" rel=\"noopener\">ROR tutorials<\/a> and start exploring!<\/p>\n<p>Bacancy Technology has dedicated, experienced, and industry\u2019s best ROR developers who have mastered Rails\u2019 basic and advanced concepts. Are you looking for assistance to help you with your Ruby on Rails project requirements? Then without any further delay, contact Bacancy Technology and <a href=\"https:\/\/www.bacancytechnology.com\/ruby-on-rails-development\" target=\"_blank\" rel=\"noopener\">hire ruby on rails developer<\/a> from us. You\u2019ll never regret your decision to work with Bacancy.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are innumerable gems available for the ROR framework. Cocoon is one of those gems. If you haven\u2019t explored much about the Cocoon Gem, then don\u2019t worry! In this step-by-step guide, we will implement Cocoon gem example and learn more about it. So, get ready to code and integrate cocoon gem! Introduction In this tutorial, [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":18397,"comment_status":"open","ping_status":"open","sticky":false,"template":"blog-new-template.php","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"no","footnotes":""},"categories":[35],"tags":[],"coauthors":[1664],"class_list":["post-18383","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ruby-on-rails"],"acf":[],"modified_by":"Chandresh Patel","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/18383","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=18383"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/18383\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/18397"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=18383"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=18383"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=18383"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=18383"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}