It is intentional that custom routes
are a bit unpleasant to use, because most of the application domain should be modeled
with CRUD and special cases should be the exception rather than the rule.
Nested resource routes
Rails has a provision to specify nested resources when generating named routes. For
example, consider a social networking application where each person can have many
friends; we can express these resource relationships with the nested route declaration:
map.resources :people do |person|
person.resources :friends
end
In this situation, the friends resources are scoped to a particular person. The URI for
a friend belonging to a person would look like /people/1/friends/2, and a person??™s
friends could be viewed at /people/1/friends.
The corresponding named routes are simple, with one minor change: they take an
extra parameter, for the person_id to which they are scoped. Given that route declaration,
we now have the following routes (note that the declaration also includes the
base people resources).
Note that we are still in a flat controller namespace. By default, those route declarations
will look for PeopleController and FriendsController. If the resources are truly
Named route URI Controller Params
people_path /people people {}
person_path(1) /people/1 people {:id => 1}
friends_path(1) /people/1/friends friends {:person_id => 1}
friend_path(1, 2) /people/1/friends/2 friends {:person_id => 1, :id => 2}
RESTful Rails | 215
nested, and friends are always scoped to a person, it may make more sense to use
controller namespaces.
Pages:
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337