【问题标题】:Active record callbacks. How are they able to access variables/scope?活动记录回调。他们如何能够访问变量/范围?
【发布时间】: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


    【解决方案1】:

    1) 同self.password。 ActiveRecord 定义方法,而不是实例变量来访问与数据库相关的内容。这就是为什么您无法使用 @password 访问它的原因。

    2) 您需要使用self.password_salt=,否则您将分配一个局部变量,而不是进行方法调用。

    PS:回调只是对对象的方法调用。唯一的区别是 Rails 为你调用它们,而不是你自己。

    【讨论】:

    • 就是这样。感谢您的澄清。 :)
    猜你喜欢
    • 2011-11-04
    • 2013-06-12
    • 2012-07-16
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多