Change the name of the :id parameter in Routing resources for Rails

Viewed 81207

I looked around on how to change the dynamic params slot and found this post that does the exact thing. The post is https://thoughtbot.com/blog/rails-patch-change-the-name-of-the-id-parameter-in

Basically what it does is, if following is the routes:

map.resources :clients, :key => :client_name do |client|
  client.resources :sites, :key => :name do |site|
    site.resources :articles, :key => :title
  end
end

These routes create the following paths:

/clients/:client_name
/clients/:client_name/sites/:name
/clients/:client_name/sites/:site_name/articles/:title

One solution is to override the def to_param method in the model, but I want this without touching the model itself.

But since its for Rails 2.x, how can I achieve the same for Rails 3?

Update

This app is using Mongoid. Not AR. So, the gem friendly cannot be used afaik.

5 Answers

In Rails 3 you can rename the id keys by using a combination of namespaces and scopes like this (not very nice though):

namespace :clients do
  scope "/:client_name" do
    namespace :sites do
      scope "/:name" do
         post "/:title" => "articles#create"
         ...
      end
    end
  end
end
Related