4

Given a one to many relationship between a user managed with devise and a "thing", my goal is to draw restful routes like:

http://host/username
http://host/username/things
http://host/username/things/1
...

I am aware of nested resources in Rails routes, but I can't figure out how to apply it to a generic User model created and managed via devise.

lbz
  • 9,560
  • 2
  • 30
  • 35

2 Answers2

13

You can use scope for this:

scope ":username", :as => "user" do
  resources :things
end

Combine this with to_param on the user model:

def to_param
  username
end

And you'll have routes such as /username/things. Be careful though, the username shouldn't contain any dots, forward slashes or standard URI characters. You may want to chuck a parameterize on the end of username to make sure.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
0

You can also use resource :user, path: ':id' do ... end

Also don't forget to define to_param in your user modal & use User.find_by_username(params[:id]) in your controller.

draw
  • 4,696
  • 6
  • 31
  • 37