如何阻止友好 id 生成数字序列来区分冲突的 slug?

How to stop friendly id from generating a numeric sequence to differentiate conflicting slug?

假设我在其 has_many 关联中对 name 有唯一性约束。这意味着我不需要将难看的数字序列添加到冲突的 slug 中。

例如,2 个 slug 可能在 game 数据库中获得相同的名称,来自 2 个不同的人,他们有一个名为 'cards' /person/1/games/cardsperson/2/games/cards 的游戏,这些是 2不同的 URL,但第二个 slug 看起来像 person/2/game/cards2bc08962-b3dd-4f29-b2e6-244710c86106。人对他们的游戏名称有名称唯一性约束,因此他们不能有 2 个名为 'cards' 的游戏,这会阻止生成 2 个相同的 slug。

问题是游戏的名称都在一个数据库中排序,因此冲突的 slug 将在不需要时添加数字序列,因此 url 变得不必要地丑陋。

希望我想要它的原因有意义。

无论如何。如何阻止将数字序列添加到冲突的 slug 中?

使用scoped functionality

class Card
   friendly_id :name, :use => :scoped, :scope => [:person]
end

要添加到已接受的答案中,还有 slug_candidates 方法:

#app/models/card.rb
class Card < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  def slug_candidates
    [
      :name,
      [:name, :person_id]
    ]
  end
end

以上将创建:

#url.com/players/1/games/cards
#url.com/players/2/games/cards-2

虽然不如 scoped 满足您的需求,但它会为您提供一些其他实现的选择。