为Rails路线添加标题 [英] Adding title to rails route

查看:90
本文介绍了为Rails路线添加标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的List对象:

I have List objects which are shown like this:

www.mysite.com/lists/123

www.mysite.com/lists/123

其中123是列表的ID。我想做的是在URL列表中添加标题,以便它提供更多信息(适用于google或其他工具)。所以我希望它看起来像这样:

Where 123 is the id of the list. What I would like to do is add the title of the list the url so it it more informative(for google or whatever). So I would like it to look like:

www.mysite.com/lists/123/title-of-list-number-123

www.mysite.com/lists/123/title-of-list-number-123

如何添加到这样的网址?如果您仅输入:
www.mysite.com/lists/123没有标题,是否应该找到标题然后重定向到新路线?

How do you go about adding to a url like this? If you just enter: www.mysite.com/lists/123 w/o the title, should it find the title and then redirect to a new route?

推荐答案

如果您希望按ID保持查找呼叫不变,则可以执行与mplacona建议相反的操作:

If you want to keep your find-calls as they are (by id), you could do the opposite of what mplacona suggested:

def to_param
  "#{id}-#{title.parameterize}"
end

使用此方法,您的find(params [:id])将起作用,因为它将字符串转换为整数(仅当数字位于字符串的开头)。因此,这实际上是可行的:

With this, your find(params[:id]) will work because it'll convert the string to an integer (can only succeed if the number is in the beginning of the string). So this is will actually work:

List.find("123-my-title")

,并且将与

List.find(123)

在此处了解有关此方法和其他方法的更多信息:< a href = http://gregmoreno.ca/how-to-create-google-friendly-urls-in-rails/ rel = nofollow noreferrer> http://gregmoreno.ca/how-to-create- google-friendly-urls-in-rails /

Read more about this and other ways to accomplish this here: http://gregmoreno.ca/how-to-create-google-friendly-urls-in-rails/

参数化将自动将字符串转换为漂亮 URL。在此处了解更多信息: http://api.rubyonrails.org/ classes / ActiveSupport / CoreExtensions / String / Inflections.html#M001367

The parameterize will automatically convert the string to a "pretty" url. Read more here: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367

如果您想要更多功能,我建议 friendly_id

If you want a bit more functionality, I'll suggest friendly_id aswell.

这篇关于为Rails路线添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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