【问题标题】:Friendly ID Random Url友好 ID 随机网址
【发布时间】:2013-04-13 06:46:12
【问题描述】:

我正在为我的网站使用友好,目前我让它在 url 中显示标题

即:/articles/hello-world

但是说当我创建页面时,它会生成一个随机数,以避免重复 所以

即:/articles/75475848

我知道如果我去掉友好的 id,它会显示数字,但是 会是

/articles/1

/articles/2

等等……

基本上我如何让它显示/articles/23456789(random number) 而不是/articles/hello-world

谢谢

【问题讨论】:

    标签: ruby-on-rails friendly-url friendly-id


    【解决方案1】:

    似乎为每篇文章生成一个 UUID(通用唯一标识符)可能是一个不错的解决方案。

    Ruby 标准库为我们提供了一个生成 UUID 的方法,因此您只需创建一个数据库字段,然后使用 before_save 回调为每篇文章提供自己的 UUID。像这样:

    class Article < ActiveRecord::Base
      before_save :set_uuid
    
      def set_uuid
        self.uuid = SecureRandom.uuid if self.uuid.nil?
      end
    end
    

    编辑:根据@olleolleolle 的评论,不需要外部依赖!

    【讨论】:

    • 或者在标准库中 - SecureRandom::uuid.
    • 谢谢!编辑了我的答案以改用它。
    【解决方案2】:

    来自 FriendlyID 文档:

    class Person < ActiveRecord::Base
      friendly_id :name_and_location
      def name_and_location
        "#{name} from #{location}"
      end
    end
    
    bob = Person.create! :name => "Bob Smith", :location => "New York City"
    bob.friendly_id #=> "bob-smith-from-new-york-city"
    

    因此,如果您为 friendly_id 提供一个生成随机数的方法,则该方法将用于生成 slug。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2016-03-11
      • 2011-02-15
      • 1970-01-01
      • 2016-08-17
      • 2010-10-23
      相关资源
      最近更新 更多