为Rails路线添加标题

编程入门 行业动态 更新时间:2024-10-26 14:31:04
本文介绍了为Rails路线添加标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有如下所示的List对象:

I have List objects which are shown like this:

www.mysite/lists/123

www.mysite/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/lists/123/title-of-list-number-123

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

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

How do you go about adding to a url like this? If you just enter: www.mysite/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)

在此处了解有关此方法和其他方法的更多信息: gregmoreno.ca/how-to-create- google-friendly-urls-in-rails /

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

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

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

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

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

更多推荐

为Rails路线添加标题

本文发布于:2023-10-31 19:17:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1547030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路线   标题   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!