There are a number of gems used in Ruby on Rails Framework. Cocoon gem is one of them; this gem is basically used for Nested forms, multiple models and in multiple attributes in one form.
Nested forms in Rails are the forms which are used for creating; updating, deleting multiple models data using a single form.
For example, we have two models user and address. If we have to save user and address data from single form here nested forms are used.
Let us consider another scenario, if we have to save one user data having multiple addresses at that time cocoon gem is very useful.
The cocoon gem generates nested form and adds/remove button for adding/removing multiple forms for the nested model (in above case “addresses”).
Simply clicking on add/remove button we can generate multiple form fields of the nested model (addresses).
This gem requires jQuery. If jQuery is not present in the project then simply add “jquery_rails” gem to gemfile.rb.
INSTALLATION STEPS FOR “COCOON” GEM:
Add following in Gemfile.rb file:
Also, add following in the application.js file:
//= require cocoon
That’s all about the installation process.
Let’s see an Example PROJECT:
For creating a Project model, controller and views using scaffold command just run:
rails g scaffold Project name:string description:string
Then create a Task model which belongs to the project:
rails g model Task description:string done:boolean project:belongs_to
Changes in rb file:
class Project < ApplicationRecord has_many :tasks, inverse_of: :project accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true end
No changes required in rb file:
class Task < ApplicationRecord belongs_to :project end
Changes in projects_controller.rb file:
def project_params params.require(:project).permit(:name, :description, tasks_attributes: [:id, :description, :done, :_destroy]) end
Changes in projects/_form.html.erb file:
Create a new file named as _task_fields.html.erb in the projects folder in view and add following code in it:
Following are the snapshots of output scenarios:
Similarly, we can remove task form from the project by clicking in remove task link present on the project form.
In the process of web application development nested forms play important roles that can be achieved by using COCOON GEM so that one can add multiple instances of nested form in a form.