views:

99

answers:

2

I'm using Ryan Bates' nifty authentication in my application for user signup and login. Each user has_many :widgets, but I'd like to allow users to browse other users' widgets. I'm thinking that a url scheme like /username/widgets/widget_id would make a lot of sense--it would keep all widget-related code in the same place (the widgets controller). However, I'm not sure how to use this style of URL in my app.

Right now my codebase is such that it permits logged-in users to browse only their own widgets, which live at /widgets/widget_id. What changes would I need to make to routes.rb, my models classes, and any place where links to a given widget are needed?

I've done Rails work before but am a newb when it comes to more complicated routing, etc, so I'd appreciate any feedback. Thanks for your consideration!

A: 

Look into nested routes. You could nest widgets inside users, like this:

map.resources :users do |users|
  users.resources :widgets
end

Which would give you URLs like these:

/users/1/widgets # all of user 1's widgets
/users/1/widgets/1 # one of user 1's widgets

Check out the routing guide for more details.

Jimmy Cuadra
A: 

The easiest would be to go with InheritedResources plugin which handles most of the legwork for you.

# routes:
map.resources :users do |user|
  user.resources :widgets
end


class WidgetsController < InheritedResources::Base
  # this will require :user_id to be passed on all requests
  # @user will be set accordingly
  # and widget will be searched in @user.widgets
  belongs_to :user
end

# no changes required to the models
Vitaly Kushner