在 Rails 路由中更改 id 参数 [英] Changing the id parameter in Rails routing
问题描述
使用 Ruby on Rails 3 的新路由系统,是否可以更改默认的 :id 参数
Using Ruby on Rails 3's new routing system, is it possible to change the default :id parameter
resources :users, :key => :username
出来以下路线
/users/new
/users/:username
/users/:username/edit
...etc
我之所以这么问,是因为虽然上面的示例很简单,但在我正在从事的当前项目中这样做会非常有帮助.
I'm asking because although the above example is simple, it would be really helpful to do in a current project I'm working on.
是否可以更改此参数,如果不可以,是否有特殊原因?
Is it possible to change this parameter, and if not, is there a particular reason as to why not?
推荐答案
如果我理解正确,你想要的是在你的 username
而不是 id
网址对吧?
If I understand you correctly, what you want is to have the username
instead of id
in your url, right?
您可以通过覆盖模型中的 to_param
方法来做到这一点.您可以在这里获取更多信息.
You can do that by overriding the to_param
method in your model. You can get more information here.
这篇关于在 Rails 路由中更改 id 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!