Cocoon Gem in Ruby on Rails - Programming Tips

Views:
 
Category: Entertainment
     
 

Presentation Description

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.

Comments

Presentation Transcript

slide 1:

Cocoon Gem in Ruby on Rails - Programming Tips 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. PREREQUISITES: 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: gem cocoon Also add following in the application.js file: // require cocoon That’s all about the installation process.

slide 2:

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 Project.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 Task.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:

slide 3:

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:

slide 4:

1 Creating a new project: 2 Adding one task in project form click on add task link to render task form: 3 Adding two tasks in project form:

slide 5:

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.

authorStream Live Help