在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?
推荐答案
如果我对您的理解正确,那么您想要的是拥有用户名
而不是 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屋!