You need to use self.
when setting attributes (which are actually 'setter' helper methods) - otherwise ruby thinks you are creating new local variables:
self.password = pswd
self.password_confirmation = pswd
質問
I'm trying to update user password using password_confirmation to confirm it.
However, I can't find a way to correctly update my password, I set password with password=
and password_confirmation=
but when I watch changed?
results, it always return false.
Any suggestion on how to solve this issue? Here is my code (change_password is called in a controller, params are correctly passed I've seen them with print):
class User < ActiveRecord::Base
acts_as_authentic
belongs_to :organization
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :organization_id, :note, :role
validates :email, :uniqueness => true
validates :role, :inclusion => { :in => Rails.configuration.available_roles }
def change_password!(pswd)
password = pswd
password_confirmation = pswd
return changed? && save
end
def change_password(old_pswd, pswd, confirm_pswd)
return false, 'Old password is incorrect' if !valid_password?(old_pswd, true)
password = pswd
password_confirmation = confirm_pswd
# update_attributes([user: [password: pswd, password_confirmation: confirm_pswd]])
print "--------- #{old_pswd} #{pswd} #{confirm_pswd} #{changed?.to_s} ------------"
return changed? && save, 'New and confirm password are not correcty'
end
end
解決
You need to use self.
when setting attributes (which are actually 'setter' helper methods) - otherwise ruby thinks you are creating new local variables:
self.password = pswd
self.password_confirmation = pswd