Tuesday, April 21, 2009

Rails and form_for() within Partials

This one tripped me up for almost 2 hours.

When using form_for() within a partial, use the variable reference instead of a symbol when specifying the form object. i.e. Use form_for(@user){|user_form|}, instead of form_for(:user){|user_form|}

I was creating a multi-model form with nested attributes using the new Rails 2.3 fields_for semantics, and the nested model field id's didn't have the numbered "*_attributes_0" suffix string. Ruling out syntax errors, I inspected the nested form objects and found that my user_form.object was nil, and thus the form_for method was not assigning the form object. When led me to find that my use of form_for(:user) was broken. form_for(@user) worked perfectly.

My conclusion may be incorrect, but it appears that using a symbolic reference as an object attribute for form_for() within a partial is broken.

The moral of the story is, just use the variable reference.

No comments: