问题
I'm new to Ruby on Rails and I'm hung up on using Active Record callbacks. I know how to use them, but I'm trying to truly understand what is happening, and I'm not getting it. My confusion has to do with variable scopes in Ruby.
Here is a simple Active Record class for a user with fields: email, password_hash, password_salt
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
#validation
validates :password, :confirmation => true
validates :email, :password, :presence => true
validates :email, :uniqueness => true
#When saving the user, encrypt the password
def encrypt_password
#First check if the password is present
if (password.present?)
#encrypt the password
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
In the method "encrypt_password", how is the variable "password" accessible? Is it the same as self.password (object var?), and is this not the same as @password? (why?)
In the actual encryption routine, I invoke self.password_salt. I noticed that I can simply type in "password_salt" (without reference to self) and it doesn't work. Why not? Why is this different from @password_salt?
Sorry if this comes across as noobish, I've spent a good couple of hours bashing away at this, and I'm struggling to understand this.
回答1:
1) It is the same as self.password. ActiveRecord defines methods, not instance variables to access stuff related to the database. That's why you cannot access it with @password.
2) You need to use self.password_salt= because otherwise you'd be assigning a local variable, not doing a method call.
PS: Callbacks are only method calls on your object. The only difference is that Rails calls them for you, not yourself.
来源:https://stackoverflow.com/questions/8648064/active-record-callbacks-how-are-they-able-to-access-variables-scope