activerecord - Rails -- auto generate read only attribute on create -


i have class read-only attribute:

class user < activerecord::base   attr_readonly :key   validates_uniqueness_of :key end 

i auto-generate :key attribute when object created , never let attribute changed after creation. tried this:

class user < activerecord::base   attr_readonly :key   validates_uniqueness_of :key    before_create :generate_key    private     def generate_key       self.key = digest::md5.hexdigest(time.now.to_s + rand(100000).to_s)[0..5]     end end 

and predictably results in error since i'm trying assign protected attribute. what's appropriate way this?

you can make key as:-

attr_accessible :key 

and add 1 more validation

validate :check_if_key_changed, :on=> :update validates_uniqueness_of :key before_create :generate_key  private   def generate_key     self.key = digest::md5.hexdigest(time.now.to_s + rand(100000).to_s)[0..5]   end  def check_if_key_changed   if self.key_changed?     errors.add(:key,"cant change key")   end end 

in way able generate key , can make sure not updated.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -