Cameron
Cameron

Reputation: 4201

Does validates_uniqueness_of work for generating a random token?

If I want to generate a random string for a token in rails, can I use validates_uniqueness_of on it? Given that this isn't something a user will input or get an error back for it needs to be unique straight away. Or am I just being stupid?

Upvotes: 0

Views: 235

Answers (2)

Maximiliano Guzman
Maximiliano Guzman

Reputation: 2035

how about:

 class Token < ActiveRecord::Base
   validates_uniqueness_of :random_key

   before_validation_on_create :create_key_until_valid

   def create_key_until_valid
     self.random_key = rand.to_s.slice(2,10)                                      
     while Token.find_by_random_key(self.random_key)
       self.random_key = rand.to_s.slice(2,10)
     end
   end
 end

Upvotes: 2

Codebeef
Codebeef

Reputation: 43996

validates_uniqueness_of will just make sure that the attribute is unique - it won't generate the value.

I'd use before_validation to create the unique value.

Upvotes: 0

Related Questions