Does validates_uniqueness_of do the job of 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? Considering that this is not something the user will enter or receive an error message, it should be unique right away. Or am I just stupid?

0


a source to share


2 answers


What 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

      



+2


a source


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



I would use before_validation to create a unique value.

0


a source







All Articles