Rails: Nested resources

2019-09-20 02:55发布

问题:

The following path throws up an error:

 = link_to 'Subscribers', user_subscribers_path(current_user)

undefined method `user_subscribers_path' for <#:0x007f9b240b3148>

I am not sure why.

I have defined my routes as follows:

  resources :users, :only => [:show, :index], :has_many => :subscribers, :shallow => true

Thanks!

EDIT rake routes does not show anything particularly useful. The only two lines with subscribers are:

users GET    /users(.:format)               users#index {:has_many=>:subscribers}
user GET    /users/:id(.:format)           users#show {:has_many=>:subscribers}

回答1:

You need to define resource subscribers in routes files as follows

resources :users do 
 resources :subscribers
end

this will create the needed path helper for your resource

For the shallow routes you can use

 map.resources :users, :shallow => true do |user|
  user.resources :subscribers 
 end