I’m not getting REST with Ruby on Rails, and I’m hoping someone here can set me straight.
Imagine that I’m building a site that keeps track of Widgets and the Users that own those Widgets. So I’d have a UsersController and a WidgetsController, and I could get a list of Widgets or Users with the index actions:
GET /users
GET /widgets
and I could get a specific User or Widget with the show actions:
GET /users/id
GET /widgets/id
That much I understand.
Where I’m getting confused is what RESTful request would I use to retrieve a list of Widgets belonging to a specific User? Is that a request sent to the UsersController or the WidgetsController? Which of the 7 RESTful actions does it use?
Is one of those situations where I’d create a custom action? I was under the impression that custom actions are supposed to be rare, but this seems like a pretty common use case.
Thanks!
The url for the list of widgets belonging to a user
foowould look like this:You then have a choice of how to do your URLs for each of those widgets. This is possible:
But I prefer this:
Your routes would look like this:
(This is from memory, I may have screwed up one or more details)
The controller method that handles
/user/foo/widgetsis theindexaction of theWidgetController. It tests for the existence of theuser_idparameter and restricts the widgets returned based on that. (Or retrieves thefoouser and sets@widgetsto@user.widgets.)Update: There’s a good overview of nested routing that answers my original question in the Rails Guides.
Update 2 Oh yes, I meant to link to some documentation as well.