[英]Rails RESTful Routes: override params[:id] or params[:model_id] defaults
I'm trying to understand how to change this rule directly on the map.resources: 我试图了解如何直接在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: 所以我会有这样的RESTful路由:
/:user/docs
/:用户/文档
/docs/:id
/ docs /:id
/docs/:doc_id/specs
/ 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. 因此,我发现在这种情况下很难跟踪
params[:doc_id]
,因为有时它的params[:id]
和有时它的params[:doc_id]
,在这种情况下,我想始终使用一个特定的名称,所以我赢了不必为我的过滤器创建两个不同的声明。
Well, I did a little bit of research and I found this patch: 好吧,我做了一些研究,发现了这个补丁:
http://dev.rubyonrails.org/ticket/6814 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上添加:key参数,以便您可以定义以后要引用的方式,这样我们就可以做到:
map.resources :docs, :key => :doc ...
so I always would call the param with params[:doc]
instead. 所以我总是用
params[:doc]
来调用param。
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? 但是实际上这个补丁有点旧(现在已经3年了),所以我想知道我们是否没有更新的并且已经内置了rails来执行此任务?
PS 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. PS我不确定模型内部定义的to_param方法,显然这并没有改变我的请求以及我仍然得到的日志:
Parameters: {"doc_id"=>"6"}
或Parameters: {"id"=>"6"}
一直。
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 这将为您提供看起来像example.com/docs/234-the-name-of-your-doc的URL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.