views:

141

answers:

3

So In my rails app I have two resources (rentals, and reservations) which belong to a user. This is the code in my routes.rb to set up the nested routes.

  map.resources :users, :has_many => :reservations, :shallow => true
  map.resources :users, :has_many => :rentals, :shallow => true
  map.resources :rentals, :only => [:index]
  map.resources :reservations, :only => [:index]

Is there a more perferred way to do this. I've done some googling but I can't find a clear answer.

Thanks in advance.

-ray

+1  A: 

You can define nested routes with blocks

map.resources :users, :shallow => true do |user|
  user.resources :reservations, :only => [:index]
  user.resources :rentals, :only => [:index]
end

I feel that this way is a bit more clear and can more easily be adjusted later when you need additional options on one of the nested resources.

The different options and the details are at the ActionController Resources API page

danivovich
Same comment as I left on kchau's answer: this does not create all the routes as the original.
ScottJ
+1  A: 

Nests the two resources under users:

  map.resources :users, :shallow => true do |users|
    users.resources :reservations, :only => :index
    users.resources :rentals, :only => :index
  end

Edit: Sorry, forgot the :shallow option.

kchau
This does not create all the routes as the original. The OP has a full list of nested routes, plus one non-nested route (index).
ScottJ
ScottJ is right, my code snippet will only produce a subset of the routes that OP wants.
kchau
+6  A: 

Your method duplicates the routes for users, as you can see by running rake routes. You can fix that by passing a block to map.resources:

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

The nested routes created will assume that you always want to access those resources in a nested fashion.

If you really need all the routes you've defined (including the non-nested rentals and reservations index) then you will need to add:

map.resources :rentals, :only => [:index]
map.resources :reservations, :only => [:index]

And I don't know of a DRYer way to do that.

ScottJ