【问题标题】:Use Numeric Sequence for Duplicate Slugs [Friendly ID]对重复的蛞蝓使用数字序列 [Friendly ID]
【发布时间】:2016-03-26 00:32:31
【问题描述】:

我注意到docs 上写着:Previous versions of FriendlyId appended a numeric sequence to make slugs unique, but this was removed to simplify using FriendlyId in concurrent code.

有没有办法恢复到这种格式?我的模型只有name,因此没有任何其他可行的slug 候选者并且(timedate 在这种情况下对于slug 候选者没有意义)。

我怎样才能改变这个(当前格式):

car.friendly_id #=> "peugeot-206"
car2.friendly_id #=> "peugeot-206-f9f3789a-daec-4156-af1d-fab81aa16ee5"
car3.friendly_id #=> "peugeot-206-f9dsafad-eamj-2091-a3de-fabsafafdsa5"

进入这个:

car.friendly_id #=> "peugeot-206"
car2.friendly_id #=> "peugeot-206-1"
car3.friendly_id #=> "peugeot-206-2"

【问题讨论】:

    标签: ruby-on-rails friendly-id


    【解决方案1】:

    我知道你说过

    (在这种情况下,对于 slug 候选人来说,时间或日期没有意义)

    但是假设您我们仅指的是时间的字符串格式而不是 unix,后者是一个数字序列,那么我想出了这个解决您的问题/疑虑的方法:

    1. 您的模型只有名称属性
    2. 您不能使用 id 附加到 slug,因为它尚未创建
    3. 您希望 slug 是唯一且递增的
    4. 你不想使用 UUID

    # app/models/car.rb
    class Car < ActiveRecord::Base
      extend FriendlyId
      friendly_id :name, use: :slugged
    
      def normalize_friendly_id(string)
        incremented_number = (Time.now.to_f * 1000000).to_i
        "#{super}-#{incremented_number}"
      end
    end
    

    所以现在可以了

    car1 = Car.create(name: "peugeot")
    car2 = Car.create(name: "peugeot")
    car3 = Car.create(name: "peugeot")
    
    car1.friendly_id #=> "peugeot-1451368076324115"
    car2.friendly_id #=> "peugeot-1451368076457560"
    car3.friendly_id #=> "peugeot-1451368076460087"
    

    注意:数字正在递增

    Time.now.to_f * 1000 将是毫秒,我正在使用 Time.now.to_f * 1000000 即 MICROSECONDS 不会同时创建,因此不会遇到 slug 冲突。如果有人认为它可以在该乘数上再添加几个零。

    【讨论】:

    • 有没有更好的方法来代替这么长的蛞蝓?它并不比使用哈希好多少,并且还显示了创建时间(这可能不是您想向最终用户显示的内容)。
    【解决方案2】:

    旧行为在特殊的module 中实现。但目前它还没有发布。因此,如果您想恢复旧行为,您可以在 Github 上的 Gemfile 中切换 friebdly_id,并将 sequentially_slugged 添加到模块列表中。

    【讨论】:

    • 这已经发布并且可以通过 use: :sequentially_slugged 而不是 :slugged 来使用
    【解决方案3】:

    “序列号”被 UUID(竞争条件)取代是有充分理由的。
    我通常使用带有 ID 的附加 slug 候选者,它由 db 维护 uniq 并且比 UUID 短得多:

    [ [:name], [:name, :id] ]
    

    【讨论】:

    • ID 对我不起作用,因为在设置候选对象之前没有创建对象(有解决方法吗?)。而且我希望避免公开透露 ID,但如果这是最好的解决方案,它会比使用 UUID 更好。
    • 我将它与globalize 一起使用,也许这就是我有 ID 的原因。解决方法:after_create:清除 slug 并再次保存(呃)?
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2012-09-30
    • 2014-03-12
    • 2016-07-27
    • 2014-05-31
    • 2012-03-31
    • 2013-02-02
    相关资源
    最近更新 更多