Reputation: 1461
I declared attr_accessor :password in the top of my model
then, I try to do
validates :password, :presence => true, :length => { :minimum => 6 }, :if => (password.present? or hashed_password.blank?)
But it throw exception and says that ruby don't know password field
why?
EDIT:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password
validates :name, :presence => true, :uniqueness => true
validates :email, :presence => true
validates :password, :presence => true, :length => { :minimum => 6 }, :if => (password.present? or hashed_password.blank?)
before_save :encrypt_password
def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.hashed_password = BCrypt::Engine.hash_secret(password, salt)
end
end
end
Upvotes: 0
Views: 1659
Reputation: 27961
Nothing to do with attr_accessible
- the problem here is that you're calling password
in the class context of the validates
class method, and so it's not defined there.
You need to provide a lambda which Rails will pass the instance being validated to:
:if => lambda { |u| u.password.present? or u.hashed_password.blank? }
Upvotes: 4