April 01, 2015

Home » » Nested Attributes in Rails 4 - Nested Model Form

Nested Attributes in Rails 4 - Nested Model Form

Posted by Unknown
0

If you have models: Survey has many Questions and Question has many anwsers.

Your models

models/survey.rb

class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

models/question.rb

class Question < ActiveRecord::Base
  belongs_to :survey
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

models/answer.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end

Your controllers

survey_controller.rb

def new
  @survey = Survey.new
  3.times do
    question = @survey.questions.build
    4.times { question.answers.build }
  end
end
The new method above will create survey with 3 questions and 4 answer for each question.

create method in survey_controller.rb

  def create
    @survey = Survey.new survey_params
    if @survey.save
      flash[:success] = "New survey has been created!"
      redirect_to surveys_path
    else
      render 'new'
    end
  end

Strong params in rails 4

# in survey_controller.rb

private

def survey_params
  params.require(:survey).permit :name, questions_attributes: [:content, :name, answers_attributes: [:content]]
end
* Change these attributes to correct your app.

Your view files

views/surveys/new.html.erb

<%= form_for @survey do |f| %>
  <%= f.error_messages %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.fields_for :questions do |builder| %>
    <%= render "question_fields", :f => builder %>
  <% end %>
  <%= f.submit "Submit" %>

<% end %>

views/surveys/question_fields.html.erb

<%= f.label :content, "Question" %>

  <%= f.text_area :content, :rows => 3 %>

  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove Question" %>



<%= f.fields_for :answers do |builder| %>
  <%= render 'answer_fields', :f => builder %>
<% end %>

views/surveys/answer_fields.html.erb

<%= f.label :content, "Answer" %>
  <%= f.text_field :content %>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove" %>








0 comments:

Post a Comment

Popular Posts

Labels

Archive

 

Blogroll

Recepies

Flickr Images

Copyright © 2014. Tutorials Blog - All Rights Reserved