了解Rails模型中的slug_candidates方法

当前用户

我正在尝试在Rails应用程序中创建漂亮的URL。我不明白#slug_candidates模型中方法内部发生了什么

class News < ApplicationRecord
  friendly_id :slug_candidates, use: [:slugged, :finders, :history]
  def slug_candidates 
    [:title,
      [:title, :id]
    ] 
  end
end

答案中也发现了类似的方法

def slug_candidates
  [
    :name,
    [:name, 2],
    [:name, 3],
    [:name, 4],
    [:name, 5],
    [:name, 6],
    [:name, 7]
  ]
end

有人可以简要说明该方法的作用吗?

fongfan999

如果我们有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将遍历该列表,直到找到尚未使用的子弹为止。

# With `slug_candidates`
def slug_candidates 
  [:title, [:title, :id]]
end

New.first # => URL: "news/title"
New.second # => URL: "news/title-2"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章