Rails 和 SEF URL:更改 link_to 中使用的键以使用与主键不同的字段
在我的 Rails 3 应用程序中,我有一个名为 User 的模型,其中包含 id 和用户名,两者都已索引且唯一。在某些视图中的某个地方,我有以下内容:
<%= link_to 'Show this user', user %>
创建一个像这样的链接:
<a href="/users/980190962">Show this user</a>
其中那个可怕的数字是 id(主键)。现在,为了网站的 SEFness,我想在使用 link_to "..."、用户的任何地方使用用户名而不是 id,但仅限于该用户模型。向 link_to 添加参数没有帮助,因为我已经在很多地方都有它了(而且我不想一直在任何地方添加另一个参数)。
如何仅针对一个模型覆盖 link_to 帮助程序的行为?
这是这个问题的完整答案,是我从已接受的答案中扣除的。我在我的用户模型中添加了以下内容:
def to_param # overridden to use username as id, and not the id. More SEF.
username
end
def self.find(id)
@user = User.find_by_id(id)
@user = User.find_by_username(id) if @user == nil
throw ActiveRecord.RecordNotFound.new if @user == nil
@user
end
现在,这使得使用 link_to 生成的所有链接都使用用户名,而 find 将尝试 id 和用户名,使其也向后兼容。
我想像我这样刚接触 Rails 的人会发现这很有用。
In my Rails 3 app, I have a model called User with id and username, both are indexed and unique. Somewhere in some views I have following:
<%= link_to 'Show this user', user %>
That creates a link like this:
<a href="/users/980190962">Show this user</a>
where that horrible number is the id (primary key). Now, for the SEFness of the site, I would like to use the username instead of the id wherever I use link_to "...", user, but only for that User model. Adding parameters to the link_to does not help, because I already have it in many places (and I do not want to have to add another parameter everywhere all the time).
How can I override the behavior of the link_to helper only for one model?
Here is a complete answer to this question, as I deducted from the accepted answer. I added following to my User model:
def to_param # overridden to use username as id, and not the id. More SEF.
username
end
def self.find(id)
@user = User.find_by_id(id)
@user = User.find_by_username(id) if @user == nil
throw ActiveRecord.RecordNotFound.new if @user == nil
@user
end
This now makes all links generated with link_to use the username, while the find will try both the id and the username, making it also backward compatible.
Thought someone as new as me to Rails would find this useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定我在说什么,但在模型中覆盖
#to_param
可能就是您正在寻找的。Not sure of what I'm saying, but overriding
#to_param
in your model may be what you're looking for.