[英]Ruby on rails: URL from ids to names/titles etc
I created model objects of from generating a scaffold, but now I want to instead of linking to 我通过生成脚手架创建了模型对象,但现在我不想链接到
/:controller/:id (/objectname/1) to /:controller/:title (/objectname/new_blog_post). /:controller /:id(/ objectname / 1)到/:controller /:title(/ objectname / new_blog_post)。 How do I do this so that links will correct link to the title and not id? 我该如何做才能使链接正确链接到标题而不是ID?
I want to go from: 我想从:
/:controller/:id
to 至
/:controller/:name
Use to param 用于参数化
class User < ActiveRecord::Base
def to_param
name.blank? ? id : name
end
end
Or look into a plugin, acts_as_sluggable and friendly_id are ones I know of. 或者看看一个插件,acts_as_sluggable和friendly_id是我所知道的。
EDIT: Oh yes and as mentioned make sure whatever you use is unique. 编辑:哦,是的,并且如上所述,请确保您使用的任何内容都是唯一的。
EDIT: 编辑:
it would work like: 它会像这样工作:
class UsersController < ActionController::Base
def index
@users = User.all
end
end
In view: 鉴于:
<% @users.each do |user| %>
<%= link_to user.name, user_path(@user.id) %>
<% end %>
And if the that users name is John then it will render /users/John after you click that link 如果该用户名是John,则在单击该链接后它将呈现/ users / John
You will need to change a few things: 您将需要更改一些内容:
You'll have to pass the title
attribute to any paths/urls when you do stuff like link_to
eg 在执行诸如link_to
类的操作时,您必须将title
属性传递给任何路径/ URL。
post_path(@post)
will become 会变成
post_path(@post.title)
You'll also have to update your finds to look for posts by title, as opposed to id eg 您还必须更新搜索结果以按标题(而不是id)查找帖子。
@post = Post.find(params[:id])
will become 会变成
@post = Post.find_by_title(params[:title])
That should get you started :). 那应该让您开始:)。 You'll obviously want to slug the title and validate the uniqueness of the title as well. 显然,您会想要塞住标题并验证标题的唯一性。
EDIT: After reading Robert Elwell's answer, maybe I misunderstood the question. 编辑:在阅读了罗伯特·艾威尔的回答后,也许我误解了这个问题。 Do you already have a route like you described for a specific object, or are you doing this with the 'basic' routes? 您是否已经有针对特定对象描述的路线,或者正在使用“基本”路线进行此操作? If the latter, you're much better off writing a custom route like Robert suggests, and then doing some of the stuff I suggested. 如果是后者,那么最好像罗伯特建议的那样编写自定义路线,然后再执行我建议的一些工作。
编写一条自定义路线 。
Use friendly_id. 使用friendly_id。
BTW, generating url isn't working for me. 顺便说一句,生成URL对我不起作用。 I had written my own to the model 我已经写了我自己的模型
def to_param
self.friendly_id
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.