【发布时间】:2011-12-27 18:40:04
【问题描述】:
我是 Ruby on Rails 的新手,我对使用 Active Record 回调很感兴趣。我知道如何使用它们,但我正试图真正了解正在发生的事情,但我不明白。我的困惑与 Ruby 中的变量范围有关。
这是一个用于用户的简单 Active Record 类,包含以下字段: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
在方法“encrypt_password”中,如何访问变量“password”?它和self.password(object var?)一样吗,这和@password 不一样吗? (为什么?)
在实际的加密例程中,我调用 self.password_salt。我注意到我可以简单地输入“password_salt”(不参考自我),但它不起作用。为什么不?为什么这与@password_salt 不同?
很抱歉,如果这让人觉得很无聊,我已经花了好几个小时来抨击这一点,但我很难理解这一点。
【问题讨论】:
标签: ruby-on-rails-3 activerecord