Tom Pinchen
Tom Pinchen

Reputation: 2497

Nested resources no route matches error

I am trying to get a basic nested resource path to work but am currently getting the following error:

No route matches {:action=>"show", :controller=>"stores"}

In my view I have the following links:

 <% if current_user %> Hello <%= current_user.email %> /
  <%= link_to 'Store', user_store_path %> 
    <%= link_to 'New Store', new_user_store_path %>
    <%= link_to 'My Profile', home_path %>
    <%= link_to 'Edit Profile', update_path %>
    <%= link_to "Logout", logout_path %> 
   <% else %>
   <%= link_to "Login", login_path %> / <%= link_to "Sign up", signup_path %>
  <% end %>

Now when I rake my routes the paths I am being given match exactly those above - user_store_path etc..

My routes file looks like this:

   resources :users do
     resources :stores
   end

   match "signup" => "users#new"
   match "home" => "users#show"
   match "update" => "users#edit"

   get "login" => "sessions#new"
   post "login" => "sessions#create"
   delete "logout" => "sessions#destroy"
   get "logout" => "sessions#destroy"

   resources :sessions

   root :to => 'sessions#new'

This really is confusing me a lot because everything I have read on the RoR website suggests that this should work. Does anyone have any ideas where I am going wrong?

Upvotes: 1

Views: 1958

Answers (2)

pdu
pdu

Reputation: 10423

resources :users do
  resources :stores
end

creates store routes which all require a given user since it is nested.

So e.g. <%= link_to 'Store', user_store_path %> is wrong because it doesn't provide any user. It should be <%= link_to 'Store', user_store_path(current_user, store) %>.

This also applies to your other links, e.g. <%= link_to 'New Store', new_user_store_path %> which should be <%= link_to 'New Store', new_user_store_path(current_user) %>

update based on your comment

No route matches {:action=>"show", :controller=>"stores" [...] occurs because you want to show a particular resource, in this example a store. Therefore, you need to pass in the store id or the store object to generate the path/url. E.g. <%= link_to 'Store', user_store_path(current_user, current_user.store.first %>. I missed that on my initial answer, sorry.

Upvotes: 3

Mik
Mik

Reputation: 4187

It is not enough to specify the path, you must also specify the objects or their id. For example:

<%= link_to 'Store', [current_user, store] %>
<%= link_to 'Store', user_store_path(user_id: current_user.id, id: store.id) %>
<%= link_to 'New Store', new_user_store_path(user_id: current_user.id) %>
#and so on

Run rake routes and you will see that in some paths you want to specify id, for example: /users/:user_id/stores/:id

http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

Upvotes: 2

Related Questions