Created
July 26, 2011 11:08
-
-
Save nikhgupta/1106507 to your computer and use it in GitHub Desktop.
Errors with Update Attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User Model | |
========== | |
require 'digest' | |
class User < ActiveRecord::Base | |
attr_accessor :password | |
has_one :profile | |
has_many :articles, :order => 'published_at DESC, title ASC', | |
:dependent => :nullify | |
has_many :replies, :through => :articles, :source => :comments | |
validates :email, :uniqueness => true, | |
:length => { :within => 5..50 }, | |
:format => { :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i } | |
validates :password,:confirmation => true, | |
:length => { :within => 4..20 }, | |
:presence => true, | |
:if => :password_required? | |
before_save :encrypt_new_password | |
def self.authenticate(email, password) | |
user = find_by_email(email) | |
return user if user && user.authenticated?(password) | |
end | |
def authenticated?(password) | |
self.hashed_password == encrypt(password) | |
end | |
protected | |
def encrypt_new_password | |
return if password.blank? | |
self.hashed_password = encrypt(password) | |
end | |
def password_required? | |
hashed_password.blank? || password.present? | |
end | |
def encrypt(string) | |
Digest::SHA1.hexdigest(string) | |
end | |
end | |
CONSOLE | |
======= | |
ruby-1.9.2-p180 :001 > u = User.find(5) | |
=> #<User id: 5, email: "me@example.com", hashed_password: "password", created_at: "2011-07-26 10:03:41", updated_at: "2011-07-26 10:03:41"> | |
ruby-1.9.2-p180 :002 > u.update_attributes(:password => "password", :password_confirmation => "password") | |
=> false | |
ruby-1.9.2-p180 :003 > u.errors | |
=> {:email=>["has already been taken"]} | |
ruby-1.9.2-p180 :004 > |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment