- 3.1 REST in a Rather Small Nutshell
- 3.2 Resources and Representations
- 3.3 REST in Rails
- 3.4 Routing and CRUD
- 3.5 The Standard RESTful Controller Actions
- 3.6 Singular Resource Routes
- 3.7 Nested Resources
- 3.8 RESTful Route Customizations
- 3.9 Controller-Only Resources
- 3.10 Different Representations of Resources
- 3.11 The RESTful Rails Action Set
- 3.12 Conclusion
3.6 Singular Resource Routes
In addition to resources, there's also a singular (or singleton) form of resource routing: resource. It's used to represent a resource that only exists once in its given context.
A singleton resource route at the top level of your routes can be appropriate when there's only one resource of its type for the whole application, perhaps something like a per-user profile.
resource :profile
You get almost the full complement of resource routes, all except the collection route (index). Note that the method name resource, the argument to that method, and all the named routes generated are in the singular.
$ rake routes profile GET /profile(.:format) {:controller=>"profiles", :action=>"show"} POST /profile(.:format) {:controller=>"profiles", :action=>"create"} PUT /profile(.:format) {:controller=>"profiles", :action=>"update"} DELETE /profile(.:format) {:controller=>"profiles", :action=>"destroy"} new_profile GET /profile/new(.:format) {:controller=>"profiles", :action=>"new"} edit_profile GET /profile/edit(.:format) {:controller=>"profiles", :action=>"edit"}
It's assumed that you're in a context where it's meaningful to speak of the profile—the one and only—because there's a user to which the profile is scoped. The scoping itself is not automatic; you have to authenticate the user and retrieve the profile from (and/or save it to) the database explicitly. There's no real magic or mind-reading here; it's just an additional routing technique at your disposal if you need it.