REST 路由和覆盖 :id 与 to_param
我的控制器使用默认的 RESTful 路由来创建、添加、编辑等,
我想将默认的 :id
更改为使用 :guuid
。所以我所做的是:
# routes.rb
resources :posts
# Post Model
class Post < ActiveRecord::Base
def to_param # overridden
guuid
end
end
这有效,但我修改后的 REST 控制器代码有类似这样的内容
def show
@post = Post.find_by_guuid(params[:id])
@title = "Review"
respond_to do |format|
format.html # show.html.erb
end
end
当我看到这段代码时..
Post.find_by_guuid(params[:id])
它看起来是错误的,但它有效。 我不明白为什么我不能这样写:
Post.find_by_guuid(params[:guuid])
为什么当我不使用它时我仍然需要传入 params[:id]
?
寻找关于我的方法是否正确或其他需要考虑的反馈。
即使它有效,并不总是意味着它是正确的。
My controller is using the default RESTful routes for creating, adding, editing etc
I want to change the default :id
to use :guuid
. So what I did was:
# routes.rb
resources :posts
# Post Model
class Post < ActiveRecord::Base
def to_param # overridden
guuid
end
end
This works but my modifed REST controller code has something like this
def show
@post = Post.find_by_guuid(params[:id])
@title = "Review"
respond_to do |format|
format.html # show.html.erb
end
end
When I see this this code ..
Post.find_by_guuid(params[:id])
it would seem wrong but it works.
I don't understand why I can't write it out like this:
Post.find_by_guuid(params[:guuid])
Why do I still have to pass in the params[:id]
when I'm not using it?
Looking for feedback on whether my approach is correct or anything else to consider.
Even though it works it doesn't always mean it's right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在控制台中输入
rake paths
,然后检查路由的输出。您会在其中一些片段中看到“:id”片段,这就是params[:id]
的来源。这是一个 Rails 约定:当您在路由中使用resources
时,参数名为id
。我不知道你是否可以改变它(同时保留资源
;否则你可以只使用匹配规则),但无论如何你不应该这样做:即使它看起来不太逻辑,它实际上有一旦您了解了 Rails 路由的工作原理,就可以理解。Type
rake routes
in your console, and check the output of the routes. You'll see the fragment ':id' in some of them, that's where theparams[:id]
comes from. It's a rails convention : when you useresources
in your routes, the parameter is namedid
. I don't know if you can change it (while keepingresources
; otherwise you could just go with matching rules), but you shouldn't anyway : even if it seems not very logic, it actually has sense, once your understand how rails routing works.