问题描述
我正在使用friendly_id gem.在portfolio.rb 中,我放置了这两行:
I am using the friendly_id gem. In the portfolio.rb I placed these two lines:
extend FriendlyId
friendly_id :title, use: :slugged
如您所见,我也在使用 slug 选项.当我创建一个标题为example"的项目时,它可以找到并且我可以在 mysite.com/projects/example
下找到该项目.现在,如果我创建具有相同标题的第二个,我会得到一个这样的标题:mysite.com/projects/example-74b6c506-5c61-41a3-8b77-a261e3fab5d3
.我真的不喜欢这个标题.我希望有一个更友好的标题,比如 example-2
.
As you can see I am also using the slug option. When I create a project with title "example" it works find and I can find the project under mysite.com/projects/example
. Now, if I create a second one with the same title I get a title for it like this one: mysite.com/projects/example-74b6c506-5c61-41a3-8b77-a261e3fab5d3
. I don't really like this title. I was hoping for a friendlier title like example-2
.
在这个问题中,RSB(用户)告诉我是它的friendly_id导致了这种情况.我想知道是否有办法创建一个更友好的.起初我想手动"检查是否存在相同的标题(在 while 循环中)并使用 example-2 或 example-3 或... example-N 分配另一个标题.
At this question, RSB (user) told me that its friendly_id that causes that. I was wondering if there is a way to create a more friendly. At first I thought of "manually" checking if the same title exists (in a while loop) and assigning another title using either example-2 or example-3 or... example-N.
但是我需要做这样的事情还是我错过了什么?有没有更简单的方法来做这样的事情?
However do I need to do something like that or am I missing something? Is there an easier way to do something like that?
推荐答案
查看文档以获取最新信息Friendly_id 的版本:
Check the documentation for the latest version of friendly_id:
一种新的候选"功能,可以轻松设置可用于唯一区分记录的备用 slug 列表,而不是附加序列.
直接来自文档的示例:
class Restaurant < ActiveRecord::Base
extend FriendlyId
friendly_id :slug_candidates, use: :slugged
# Try building a slug based on the following fields in
# increasing order of specificity.
def slug_candidates
[
:name,
[:name, :city],
[:name, :street, :city],
[:name, :street_number, :street, :city]
]
end
end
这篇关于更改友好 ID 的唯一生成标题名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!