Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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",
             POST     /profile(.:format)      {:controller=>"profiles",
             PUT      /profile(.:format)      {:controller=>"profiles",
             DELETE   /profile(.:format)      {:controller=>"profiles",
 new_profile GET      /profile/new(.:format)  {:controller=>"profiles",
edit_profile GET      /profile/edit(.:format) {:controller=>"profiles",

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.

  • + Share This
  • 🔖 Save To Your Account