Ruby-on-rails – rails nested attributes

nested-attributesnested-formsruby-on-railsruby-on-rails-3

I am using rails 3.0.0.beta3 and I am trying to implement form with nested attributes using :accepts_nested_attributes_for.

My form is nested to three levels: Survey >> Question >> Answer.

Survey has_many Questions, and Question has many Answers.

Inside the Survey model, there is
:accepts_nested_attributes_for :questions

and inside the question mode, there is
:accepts_nested_attributes_for :answers

Everything is working fine except when I add a new answer to an existing question, it doesn't get created. However, if I make changes to the corresponding question while creating the answer, I can successfully create the answer.

This example is exactly similar to a railscast:
http://railscasts.com/episodes/197-nested-model-form-part-2

but doesn't work in rails3 (at least in my case).

Please let me know if there is any issue with nested attributes in Rails 3.

Thanks in advance.

Best Answer

If you are using attr_accessible make sure that you include the nested attributes

class Survey < ActiveRecord::Base
  accepts_nested_attributes_for :questions
  attr_accessible :questions_attributes
end

class Question < ActiveRecord::Base
  accepts_nested_attributes_for :answers
  attr_accessible :answers_attributes
end

Also, see my comment here about nested attributes and model validations if you are still having trouble. Validations misfiring in a form with multiple models

Related Topic