Rails RESTful Routes: override params[:id] or params[:model_id] defaults

2.4k views Asked by At

I'm trying to understand how to change this rule directly on the map.resources:

supposing I have a route:

map.resource :user, :as => ':user', :shallow => true do |user|
    user.resources :docs, :shallow => true do |file|
        file.resources :specs
    end
end

so I would have RESTful routes like this:

/:user/docs

/docs/:id

/docs/:doc_id/specs

So I see that is difficult to track the params[:doc_id] on this case because sometimes its params[:id] and sometimes its params[:doc_id] and in this case I would like to always call for one specific name so I won't have to create two different declarations for my filters.

Well, I did a little bit of research and I found this patch:

http://dev.rubyonrails.org/ticket/6814

and basically what this does is give you the ability to add a :key parameter on you map.resources so you can defined how you would like to reference it later so we could have something like:

map.resources :docs, :key => :doc ...

so I always would call the param with params[:doc] instead.

But actually this patch is a little bit old (3 years now) so I was wondering if we don't have anything newer and already built-in for rails to do this task?

P.S I'm not sure about that to_param method defined inside the model, apparently this didn't change anything on my requests, and on the logs I still getting: Parameters: {"doc_id"=>"6"} or Parameters: {"id"=>"6"} all the time.

1

There are 1 answers

2
bensie On

One method of making the parameters a little more friendly without writing fully custom routes is

# docs_controller.rb
def show
  @doc = Doc.find(params[:doc].to_i)
end

# doc.rb
def to_param
  [ id, permalink ].join("-")
  # assumes you're storing a permalink formatted version of the name of your doc
end

# routes.rb
map.resources :docs

This will give you URLs that look something like example.com/docs/234-the-name-of-your-doc