Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 26th, 2012  |  syntax: None  |  size: 1.69 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Adding Rails model attribute results in RecordNotSaved errors
  2. class User < ActiveRecord::Base
  3.   attr_accessor :password
  4.   attr_accessible :name, :email, :password, :password_confirmation
  5.  
  6.   email_regex = /A[w+-.]+@[a-zd-.]+.[a-z]+z/i
  7.  
  8.   validates :name,  :presence => true,
  9.                     :length   => { :maximum => 50 }
  10.  
  11.   validates :email, :presence   => true,
  12.                     :format     => { :with => email_regex },
  13.                     :uniqueness => { :case_sensitive => false }
  14.  
  15.   validates :password,  :presence     => true,
  16.                         :confirmation => true,
  17.                         :length       => { :within => 6..40 }
  18.  
  19.   before_save :encrypt_password
  20.   before_save :confirmed_false
  21.  
  22.   def has_password?(submitted_password)
  23.     encrypted_password == encrypt(submitted_password)
  24.   end
  25.  
  26.   def self.authenticate(email, submitted_password)
  27.     user = find_by_email(email)
  28.     return nil if user.nil?
  29.     return user if user.has_password?(submitted_password)
  30.   end
  31.  
  32.   private
  33.  
  34.     def confirmed_false
  35.       self.confirmed = false if new_record?
  36.     end
  37.  
  38.     def encrypt_password
  39.       self.salt = make_salt if new_record?
  40.       self.encrypted_password = encrypt(password)
  41.     end
  42.  
  43.     def encrypt(string)
  44.       secure_hash("#{salt}--#{string}")
  45.     end
  46.  
  47.     def make_salt
  48.       secure_hash("#{Time.now.utc}--#{password}")
  49.     end
  50.  
  51.     def secure_hash(string)
  52.       Digest::SHA2.hexdigest(string)
  53.     end
  54.                                                               1,1           Top
  55.        
  56. class User < ActiveRecord::Base
  57.   # unlike before_save it's only run once (on creation)
  58.   before_create :set_registration_date
  59.  
  60.   def set_registration_date
  61.     registration_date = Time.now # or Date.today
  62.   end
  63. end