我有如下所示的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路线添加标题
发布评论