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.

form_for doesn't work with new singleton nested resource

#3675

Using a singleton nested resource, such as:

map.resources :users do |users|
  users.resource :position
end

form_for doesn't work when the nested resource is being added.

For example, in the controller:

def new
  @user = User.find(params[:user_id])
  @position = @user.build_position
end

and in the view:

form_for [:user, @member] ...

will throw an exception: undefined method user_positions_path'

The edit action is identical except the nested resource exists, so in the controller: @position = @user.position instead of @user.build_position. Using form_for [:user, @member] in the edit view creates a form with the correct singular route and put method. It fails to work only when the nested resource is a new record.

I believe the problem is in the polymorphic_url helper, used by apply_form_for_options! in form_for. The helper determines inflection based on new_record? for some reason. If the record is new the inflection is plural. This obviously fails for new singleton nested resources. Here is the pertinent section of polymorphic_url:

inflection =
  case
  when options[:action].to_s == "new"
    args.pop
    :singular
  when record.respond_to?(:new_record?) && record.new_record?
    args.pop
    :plural
  else
    :singular
  end

It's possible to work around this using a different form_for syntax to explicitly set the URL, but this seems like a bug because the behavior is inconsistent between the new and edit actions.

Reported by Jake Paul · January 9th, 2010 @ 07:35 PM

State: duplicate
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Jake Paul
    Jake Paul

    Oops, it should say form_for [:user, @position] instead of form_for [:user, @member]. My mistake.

    January 9th, 2010 @ 07:37 PM

  2. Ben Orenstein
    Ben Orenstein

    I've got a failing test for this in rails3 beta 3. Working on a patch.

    May 16th, 2010 @ 08:50 PM

  3. Rizwan Reza
    Rizwan Reza
    • No changes were found…

    May 19th, 2010 @ 10:19 AM

  4. Rizwan Reza
    Rizwan Reza
    • No changes were found…

    May 19th, 2010 @ 11:50 AM

  5. Rizwan Reza
    Rizwan Reza
    • No changes were found…

    May 21st, 2010 @ 12:45 AM

  6. Andrew White
  7. Jake Paul
    Jake Paul

    @Andrew Looks like it is, probably.

    June 7th, 2010 @ 02:11 PM

  8. DHH
    DHH
    • State changed from new to duplicate

    June 8th, 2010 @ 08:38 PM