R – Can controller names in RESTful routes be optional

routingruby-on-rails

With a standard map.resource routing mechanics and several nested resources the resultant routes are unnecessarily long. Consider the following route:

site.org/users/pavelshved/blogs/blogging-horror/posts/12345

It's easy to create in routes.rb, and I'm sure it follows some kind of beneficial routing logic. But it's way too long and also seems like it's not intended to be human-readable.

A nice improvement would be to drop controller names, so it looks like:

site.org/pavelshved/blogging-horror/12345

Clear, simple, short. It may become ambiguous, but in my case I'm not going to name any user "users", for instance.

I tried setting :as => '', but it yields routes like this: site.org//pavelshved//blogging-horror//12345 when generating them by standard helpers.

Is there a way to map resources in such a way, that controller names become optional?

Best Answer

You're looking for the :path_prefix option for resources.

map.resources :users do |user|
  user.resources :blogs do |blog|
    blog.resources :posts, :path_prefix => '/:user_login/:blog_title/:id'
  end
end

Will produce restful routes for all blogs of this form: site.org/pavelshved/bogging-horror/posts/1234. You'll need to go to a little extra effort to use the url helpers but nothing a wrapper of your own couldn't quickly fix.

The only way to get rid of the posts part of the url is with named routes, but those require some duplication to make restful. And you'll run into the same problems when trying to use route helpers.

Related Topic