Rails更改默认URL

时间:2011-09-15 23:07:53

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

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

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

是的,在to_param模型中定义User

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 :(得分:0)

将此添加到您的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(通用唯一标识符)的重点