覆盖 Rails 中生成的 Restful url 助手
假设我有一个 Page 资源,并且特定实例的 id = 5 和 permalink = foobar。
通过 resources :pages
我可以使用 <%= link_to @page.title, @page %>
输出 url“/pages/5”。
我如何让它输出“/pages/foobar”?同样,编辑网址...如何使 edit_page_path(@page)
输出“/pages/foobar/edit”?
更新
到目前为止,答案都说要覆盖 Page.rb 中的 to_param
,这是一个很好的开始。每个+1。但是如果我想要 <%=link_to @page.title, @page%>
输出“/:permalink”而不是“/pages/:permalink”怎么办?我会接受随之而来的答案。
Lets say I have a Page resource, and a particular instance has id = 5 and permalink = foobar.
With resources :pages
I can use <%= link_to @page.title, @page %>
which outputs the url "/pages/5".
How would I make it output "/pages/foobar" instead? Likewise with the edit url... How do I make edit_page_path(@page)
output "/pages/foobar/edit"?
UPDATE
Answers so far have said to override to_param
in Page.rb which is a great start. +1 to each. But what if I want <%=link_to @page.title, @page%>
to output "/:permalink" rather than "/pages/:permalink"?? I'll accept the answer that comes up with that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以重写模型中的
to_param
方法,该方法将告诉 Rails 使用什么而不是主键进行路由。例如,
参数化调用使您的标题 URL 友好,您可能还会注意到 self.id 的使用,建议您这样做,以防您有重复的标题。
You can override the
to_param
method in your model which will tell Rails what to use instead of your primary key for routing.For example
The parameterize call makes your title URL friendly, you might also notice the use of self.id, this is recommended in case you have a duplicate title.
您需要覆盖模型中的 to_param 方法以返回所需的字段。 这是一篇包含一些示例的博文:
You need to overide to_param method in your model to return the field you want. Here's a blog post with some examples:
您想使用永久链接。
将其添加到您的模型中:
这假设您有一个标题。
一旦你得到这个你想要查找 permalink-fu,或者它实际上非常简单使用保存后执行您自己的操作:
class Post
end
确保将
peramlink
作为字段添加到模型中。You want to use a permalink.
Add this to your model:
This assumes that you have a title.
Once you get this you want to look look up permalink-fu, or it's actually really simple to do your own with an after save:
class Post
end
Make sure you add
peramlink
as a field to your model.