Search code examples
ruby-on-rails-3routesnested-resources

Nested Resources without ID of parent in the route


I have two resources:

resources :users do
 resources :cars
end

The association is:

  • A user can have many cars
  • A car belongs to a user

When doing that kind of nested resourcing, I get urls like:

/users/:id/cars/new 

My question is:

If it makes more sense to do just /cars/new (without the /users/:id) because I get the :id from the current_user logged in, how would I solve that in the routes?


Solution

  • I wouldn't use nested routes at all. You can have nested models without having to have nested routes. Just load the current user from the session (you're probably doing this already), and make sure no one can access the cars controller unless they're logged in.