I've been trying to get the FormBuilder variant of fields_for to work for a few weeks now, but I can't seem to find what I feel to be the correct solution, and I think there may be a bug preventing me from realizing my goal.
If I create a form for a model, where the controller has already set the instance variable:
@user = User.new # (or current_user for an edit)
Then the view has (I'll leave out tags):
form_for :user, :url => user_url(@user), :html => { :method => :put, :multipart => true } do |f|
Now I add a nested model (Contact). And let's say that @user.contact doesn't exist yet since we are in the 'new' controller.
Then the view would also have:
f.fields_for :contact do |cf|
-
and then maybe...
cf.error_messages
However, when I do this, I receive the error:
`@user[contact]' is not allowed as an instance variable name
If, however, I instead explicitly create @user.contact = Contact.new in the users_controller.new, and then write the above fields_for like this:
f.fields_for @user.contact do |cf|
Then everything works just fine. (I do have to create @user.contact or I receive another error pertaining to 'user[nil_value]' not being valid)
The weird thing is, that I debugged a bit, and found that the object_name which is being passed to eventually give the error above is equal to 'user[contact]' in BOTH cases. So somehow, the instance variable name is only not allowed if the variable (@user.contact) has not been instantiated?
This doesn't seem right. If there is in fact a way of doing this differently and correctly to make it work, then I feel that the documentation should be updated to include using FormBuilder.fields_for differently than the normal fields_for.