Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Nested fields_for doesn't work when passed name of field

#756

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|

  1. 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.

Reported by Glenn Powell · August 4th, 2008 @ 06:33 PM

State: stale
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Glenn Powell
    Glenn Powell

    I'd appreciate it if someone could comment on whether this is a bug experienced by anyone else? Or whether there is a correct solution.

    Thanks.

    August 7th, 2008 @ 09:47 AM

  2. Jim Lindley
    Jim Lindley

    Glenn,

    This is currently expected although of course frustrating. Some work is being done in edge to alleviate this issue.

    There is a discussion going on in rails-core about this, too.

    August 9th, 2008 @ 09:55 PM

  3. Glenn Powell
    Glenn Powell

    Thanks Jim, I'll keep following the progress.

    August 10th, 2008 @ 07:43 AM

  4. josh
    josh
    • State changed from new to stale

    November 22nd, 2008 @ 07:39 PM

  5. Ryan Bigg
    Ryan Bigg

    Automatic cleanup of spam.

    October 9th, 2010 @ 10:00 PM

  6. bingbing