更改 Rails 路由中的 id 参数 [英] Changing the id parameter in Rails routing

查看:100
本文介绍了更改 Rails 路由中的 id 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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?

推荐答案

如果我理解正确,您想要的是在您的网址,对吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆