rails: link_to / form_for doesn't work for singular resource

In my routes I have

resource :company

and in my views

<% form_for(@store) do |f| %>
    …
<% end %>

When

new action gets an error when rendering

undefined method hash_for_companies_path’ for #Module:0x00000102bfd3f0`

The stack trace reviels that the problem occurs in

lib/action_dispatch/routing/polymorphic_routes.rb:133:in polymorphic_url’`

edit action can render without errors but the forms url is /company.4 where 4 is the id of the company.

This seems to be a bug that has been around for a very long time so I think it’s time to fix it.

About this issue

  • Original URL
  • State: closed
  • Created 13 years ago
  • Reactions: 3
  • Comments: 67 (40 by maintainers)

Commits related to this issue

Most upvoted comments

For anyone landing here via google, this is what got implemented: http://edgeguides.rubyonrails.org/routing.html#singular-resources

In short, add something like resolve('User') { [:user] } after you define the singular resource in routes.rb, where ‘User’ is the class name and :user is the resource name.

To anyone stumbling upon this issue, the workaround is quite simple. Given:

resource :billing_info

You generate the form_for call like this:

= form_for @billing_info, url: billing_info_path do |f|

Not sure if it can help to fix the overall problem but I helped myself the following way, since https://github.com/rails/rails/issues/1769#issuecomment-9556381 did not work properly for my new action

form_for(@equipment, :url=> {:action=> (@equipment.new_record? ? 'create' : 'update')}) do |f|

EDIT: slightly modified to make it work also when validation errors come up.

Couldn’t this be fixed in the latest rails implementation by changing the behavior of form_with?

In case anybody is looking for a workaround:

class Company < ActiveRecord::Base
  model_name.instance_variable_set(:@route_key, 'company')
end

http://stackoverflow.com/a/16229154/1149074

Yeah, it does handle both :create and :update actions.

Yep, here too, my first time with singular resource, lost 3h coz i was blaming myself like a first

i think this bug should be written in rails guides somewhere.

for anyone using a singular resource, they will eventually find themselves on this bug page. better to announce first