Create Nested form In Ruby on Rails 4.1

In Rails we create simple form and also sometimes we need nested form. In Rails we can easily do that using gem “nested_form”.

let's create a project using “nested_form”. Before that I would like to ask you to have a look on nested_attribute_documentation(http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for).

1) Create a new Rails 4 Project.
    rails new nested_app

2) Include the gem in your gem file.
  gem "nested_form"

3) run bundle install
 bundle install

4) Generate the necessary javascript file.
  rails g nested_form:install

5) Include the javascript file in the asset pipeline. in the application.js add the below line.
 //= require jquery_nested_form

6) Let say we have a Exam model and one Exam can have multiple Questions.So lets create the Exam model.

class Exam < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions, :allow_destroy => true
end

Now create the Question Model

class Exam < ActiveRecord::Base
  belongs_to :exam
end


7) Now lets create the new action for the Exam Controlle


  def new
    @exam = Exam.new
    @exam.questions.build
  end

8) Now create the New form


= nested_form_for @exam, do |f|
  .form-group
    %label.col-sm-2.control-label Survey Name
    .col-sm-10
      = f.text_field :name, class: 'form-control'
  = f.fields_for :questions do |question|
    .form-group
      %label.col-sm-2.control-label Question
      .col-sm-10
        = question.text_field :question_body, class: 'form-control'    
    .form-group
      %label.col-sm-2.control-label
      .col-sm-10.checkbox
        = question.check_box :_destroy
        Remove Question
  %p
    = f.link_to_add "Add Another Question", :questions
  %p= f.submit "Submit"

9) Check the link_to_add helper In
/gems/nested_form-0.3.2/lib/nested_form/builder_mixin.rb line no 19 for details.


10) Now as we are using rails 4 we need the permit all the attributes.

In the Controller add a private method.

def exam_params
  params.require(:exam).permit(:name, :questions_attributes => [:id, :question_body, :_destroy])
end

And our create action should be like 

 def create
    @exam = Exam.new(exam_params)
    if @exam.save
      redirect_to exam_path(@exam)
    else
      render :new
    end

  end

Important Points to remember that in the exam_params method in side the question_attributes you must permit the id for edit and update action.

For more information I will request you to check the below links

https://github.com/ryanb/nested_form
http://railscasts.com/episodes/196-nested-model-form-revised?view=comments





Comments

Post a Comment

Popular posts from this blog

Debug Nodejs inside docker container

Swap primary keys between two records in the same table in Postgres

How to add a bootstrap table with fixed header and scrollable body