In one of my applications I ran into a situation where I needed to have a single form handle a model as well as several of its associations. Meaning I needed the form to handle CRUD events for the model plus the associated models auto-magically. With that objective I remembered a RailsCast.com video cast explaining how to use the ActiveRecord ‘accepts_nested_attributes_for’ method.
So I jumped on the web and coded along while I watched the cast. But for some strange reason the code from the cast just wouldn’t work. When I saved the survey no associated questions were saved to the database despite the fact that the survey came back as successfully saved. So I triple checked that I had it all correct. Once I was satisfied that it was correct I started digging deeper when I noticed in the passenger logs in my console the following error message hidden nicely within the POST printout and the SQL statements.
<<<>>>
WARNING: Can’t mass-assign protected attributes: questions_attributes
<<<>>>
That made me think, Rails has started doing a much better job protecting our applications from Mass-Assignment attacks by requiring us to explicitly set the model attributes which are accessible and can be directly updated via a form post. I then reviewed the POST parameters to see what was being returned by the form (see below).
<<<>>>
Parameters: {“utf8″=>”✓”, “authenticity_token”=>”8XugXn/UwE+m4m2BR2pfTy7oVfUI+jKnPYaSNwKiD1s=”, “survey”=>{“name”=>”test”, “questions_attributes”=>{“0″=>{“content”=>”question1”}, “1”=>{“content”=>”question2”}, “2”=>{“content”=>”question3”}}}, “commit”=>”Submit”}
<<<>>>
Within the parameter list for the survey sent back by the form I noticed the addition of the ‘questions_attributes’ hash which holds each question with its associated hash of fields and values. Being that the ‘questions_attribute’ is a newly introduced attribute to a survey via the ‘accepts_nested_attributes_for’ method it now becomes filtered by Rails as NOT mass-assignable.
Once I added ‘questions_attributes’ to the survey model’s ‘attr_accessible’ method and retested it worked without an issue. Hope this helps those who might be stuck trying to get nested forms to work.
Published by