了解 Rails 模型中的 slug_candidates 方法
Understanding slug_candidates method in Rails model
我正在尝试在我的 Rails 应用程序中创建漂亮的 URL。我无法理解模型中 #slug_candidates
方法内部发生的情况。
class News < ApplicationRecord
friendly_id :slug_candidates, use: [:slugged, :finders, :history]
def slug_candidates
[:title,
[:title, :id]
]
end
end
在一篇answer中也找到了类似的方法:
def slug_candidates
[
:name,
[:name, 2],
[:name, 3],
[:name, 4],
[:name, 5],
[:name, 6],
[:name, 7]
]
end
有人可以简要解释一下该方法的作用吗?
如果我们有 2 个 news
具有相同的标题,那么 slugs
将是相同的。所以我们无法识别它们。例如:
New.all
# => [#<New id: 1, tile: "Title">, #<New id: 2, tile: "Title">]
# Without `slug_candidates`
New.first # => URL: "news/title"
New.second # => URL: "news/title"
# => We cannot find the second one.
现在 slug_candidates
提供了一个变体列表,FriendlyId 将遍历该列表,直到找到一个尚未被捕获的 slug。
# With `slug_candidates`
def slug_candidates
[:title, [:title, :id]]
end
New.first # => URL: "news/title"
New.second # => URL: "news/title-2"
我正在尝试在我的 Rails 应用程序中创建漂亮的 URL。我无法理解模型中 #slug_candidates
方法内部发生的情况。
class News < ApplicationRecord
friendly_id :slug_candidates, use: [:slugged, :finders, :history]
def slug_candidates
[:title,
[:title, :id]
]
end
end
在一篇answer中也找到了类似的方法:
def slug_candidates
[
:name,
[:name, 2],
[:name, 3],
[:name, 4],
[:name, 5],
[:name, 6],
[:name, 7]
]
end
有人可以简要解释一下该方法的作用吗?
如果我们有 2 个 news
具有相同的标题,那么 slugs
将是相同的。所以我们无法识别它们。例如:
New.all
# => [#<New id: 1, tile: "Title">, #<New id: 2, tile: "Title">]
# Without `slug_candidates`
New.first # => URL: "news/title"
New.second # => URL: "news/title"
# => We cannot find the second one.
现在 slug_candidates
提供了一个变体列表,FriendlyId 将遍历该列表,直到找到一个尚未被捕获的 slug。
# With `slug_candidates`
def slug_candidates
[:title, [:title, :id]]
end
New.first # => URL: "news/title"
New.second # => URL: "news/title-2"