NoMethodError with renamed nested resources (false route using link_to)

210 views Asked by At

I've ran into a problem which causes link_to @resource to fail.

My view:

<% @test_thing = Bar.first #This one belongs to Foo.first %>
<%= link_to "test link", @test_thing %>

produces this error:

NoMethodError
undefined method `bar_path' for #<#<Class:0x007fd799bc1088>:0x007fd799bc8400>

Why does rails not produce the correct route using thing1_thing2_path?

routes.rb:

resources :foo, as: "thing1", path: "thing2" do
  resources :bar, as: "thing2", path: "thing2"
end

In my models, "Foo" has_many :bars and "Bar" belongs_to :foo

rake routes:

thing1_thing2_index GET    /thing2/:thing1_id/thing2(.:format)          bar#index
                    POST   /thing2/:thing1_id/thing2(.:format)          bar#create
  new_thing1_thing2 GET    /thing2/:thing1_id/thing2/new(.:format)      bar#new
 edit_thing1_thing2 GET    /thing2/:thing1_id/thing2/:id/edit(.:format) bar#edit
      thing1_thing2 GET    /thing2/:thing1_id/thing2/:id(.:format)      bar#show
                    PATCH  /thing2/:thing1_id/thing2/:id(.:format)      bar#update
                    PUT    /thing2/:thing1_id/thing2/:id(.:format)      bar#update
                    DELETE /thing2/:thing1_id/thing2/:id(.:format)      bar#destroy
       thing1_index GET    /thing2(.:format)                            foo#index
                    POST   /thing2(.:format)                            foo#create
         new_thing1 GET    /thing2/new(.:format)                        foo#new
        edit_thing1 GET    /thing2/:id/edit(.:format)                   foo#edit
             thing1 GET    /thing2/:id(.:format)                        foo#show
                    PATCH  /thing2/:id(.:format)                        foo#update
                    PUT    /thing2/:id(.:format)                        foo#update
                    DELETE /thing2/:id(.:format)                        foo#destroy
               root GET    /                                            bar#index

I'm using rails 4, but I had the same problem with rails 3.
I fell like it's a bug in rails, or am I doing something wrong?

2

There are 2 answers

8
janfoeh On BEST ANSWER

Do not rename your routes. Remove the as: argument:

resources :foo, path: "thing2" do
  resources :bar, path: "thing2"
end

Apart from that, you need to hand it both objects in order to produce the correct path:

<%= link_to "test link", [@test_thing.foo, @test_thing] %>
3
Thyago B. Rodrigues On

Have you tried passing the link explicitly? Something like:

<%= link_to "test link", bar_path(@test_thing) %>

...or whatever the correct *_path(variable) you should be using?

(Sorry, the test, and bar, and thing1, thing2 things got really confusing over here :P)