Is this possible?
I’d like to view all the products for a User and also all of the
entire products. From what I’ve tried, this does not work:
map.resources :users do |users|
users.resources :products
end
map.resources :products
Is this possible?
I’d like to view all the products for a User and also all of the
entire products. From what I’ve tried, this does not work:
map.resources :users do |users|
users.resources :products
end
map.resources :products
You have to use a name_prefix for the nested resources.
Jamis B. wrote about it two months ago:
http://weblog.jamisbuck.org/2007/2/5/nesting-resources
cheers
– bobes
Actually my last post didn’t work. It would read the User id as the
action and the user_products as the id. I changed my routes to this
with success:
map.resources :user_products, :path_prefix => “users/:user_id”
Is this the best way to do this?
Looks like my second post didn’t go through. Here is what I had
map.resources :users do |users|
users.resources :products, :controller => “user_products”
end
map.resources :products
So you’ve got a ProductsController and UserProductsController? If so,
then
this could be a good way to go.
If the views are the same for user products and all products than having
one
controller and one set of views is a better solution.
The routes would be:
map.resources :users do |users|
users.resources :products, :name_prefix => “user_”
end
map.resources :products
And in actions you would have something like:
def index
params[:user_id].nil? ? Products.find(:all) : User.find
(params[:user_id]).products
end
You could also extract the condition to a before_filter, let me know if
you
have any problems with this…
– bobes
I actually needed to use the same views so this works perfectly. I
ended up using an if/else loop because I needed to render one
different view.
Thanks!
(now I have to go back and delete all the user_products files …)
Thanks a lot bobes! Specifically comment number 15 was exactly what I
was looking for. My routes now look like this:
map.resources :users do |users|
users.resources :products, :controller => “user_products”
end
map.resources :products
Now I obviously had to create an extra controller:
UserProducts < ApplicationController
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs