Take the 2-minute tour ×

Im using rails for an app and I scaffolded the User database. I have a show.html.erb page for each user, but currently the URL's are /users/1 or /users/2, I want the URL's to be a random number, or the timestamp of creatation. So something like /users/201109123121 or even just a random;y generated number.

Is there a way to do this?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Yes, define to_param in your User model:

def to_param

And define the timestamp attribute on your model and set it in a before_create:

class User < ActiveRecord::Base
  before_create :set_timestamp

  # model code goes here
  def set_timestamp
    self.timestamp = created_at.to_i

But if two users were created at precisely the same second, you will run into trouble. You may want to make this slightly more random than that. You will also now need to find them based on that field:

share|improve this answer
+1 on this not being a great idea; consider using a GUID instead if it's really important. –  Dave Newton Sep 16 '11 at 0:52
add comment

Add this to your Gemfile

gem 'uuidtools'

Then do

class User < ActiveRecord::Base
    before_create :set_uuid

    # model code goes here
    def set_uuid
        self.uuid = UUIDTools::UUID.timestamp_create.to_s

Then you request it like so.


Unlike the above answer this should significantly reduce the likelihood of a race condition as that's the point of uuid (universal unique identifier)

share|improve this answer
add comment

Your Answer


