21

I'm using Rails 3 and I have two models EquipmentGroup and Reservation. I want reservations to be a nested resource of equipment groups so that I can access them with URLs like:

/equipment_groups/:equipment_group_id/reservations/:id

However, I don't want to create routes for the equipment groups. I can achieve this through the following, but it seems like a hack:

resources :equipment_groups, :only => [] do
  resources :reservations
end

Is there a better way to do this? I can't seem to find an answer easily in the documentation.

Courtney
  • 231
  • 1
  • 6

2 Answers2

9

Your approach - it's a standard approach, there is nothing better.

kaleb4eg
  • 2,255
  • 1
  • 18
  • 13
0

I can think of a few ways of doing this. One way is what you've done above. However, it seems like you have no need to expose the equipment groups controller or any of its actions, so the following should do just fine:

scope "/equipment_groups" do
    resources :reservations
end

The scope block will append "/equipment_groups" to every route in it. This will essentially "fake" a nested route.

Logan Leger
  • 662
  • 3
  • 10
  • 3
    By using `scope` instead of `resources`, you lose some of the magic of url generation. For instance, `equipment_group_reservation_path(@equipment_group, @reservation)` will not work. I prefer the solution suggested in the question itself, and I do not consider it a hack. – YWCA Hello May 23 '13 at 17:07
  • This will not work! with this approach you will have route which is similar but without parent ID and without any helpers for generating routes. – kaleb4eg Jun 12 '15 at 08:54