【问题标题】:Rails change default URL'sRails 更改默认 URL
【发布时间】:2011-09-15 23:07:52
【问题描述】:

我正在为一个应用程序使用 Rails,并且我搭建了用户数据库。我为每个用户都有一个 show.html.erb 页面,但目前 URL 是 /users/1 或 /users/2,我希望 URL 是一个随机数,或者是创建的时间戳。所以像 /users/201109123121 甚至只是一个随机的;y 生成的数字。

有没有办法做到这一点?

【问题讨论】:

    标签: database ruby-on-rails-3 url routes


    【解决方案1】:

    是的,在您的 User 模型中定义 to_param:

    def to_param
      timestamp
    end
    

    并在模型上定义timestamp 属性并将其设置为before_create:

    class User < ActiveRecord::Base
      before_create :set_timestamp
    
      # model code goes here
      def set_timestamp
        self.timestamp = created_at.to_i
      end
    

    但是如果两个用户是在同一秒创建的,你就会遇到麻烦。你可能想让这个稍微随机一些。您现在还需要根据该字段找到它们:

      User.find_by_timestamp(params[:id])
    

    【讨论】:

    • +1 这不是一个好主意;如果它真的很重要,请考虑使用 GUID。
    【解决方案2】:

    将此添加到您的 Gemfile 中

    gem 'uuidtools'
    

    那就做吧

    #models/user.rb
    class User < ActiveRecord::Base
        before_create :set_uuid
    
        # model code goes here
        def set_uuid
            self.uuid = UUIDTools::UUID.timestamp_create.to_s
        end
    end
    

    然后你就这样请求它。

    User.find_by_uuid(params[:id])
    

    与上述答案不同,这应该会显着降低竞争条件的可能性,因为这是 uuid(通用唯一标识符)的关键

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 2018-10-12
      • 2016-10-05
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多