Search code examples
ruby-on-railsroutesnested-resources

Multiple Nested Routes, is there a better way to do this?


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


Solution

  • 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.