Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1nested-resources

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?


Solution

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