活动记录回调。他们怎么能够访问变量/范围有多大? [英] Active record callbacks. How are they able to access variables/scope?

查看:271
本文介绍了活动记录回调。他们怎么能够访问变量/范围有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Ruby on Rails的,我挂在使用Active Record的回调。我知道如何的使用的他们,但我想真正的明白的正在发生的事情,而且我没有得到它。我的困惑,是因为有在Ruby中变量的作用域。

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.

下面是与域用户的简单的Active Record类:电子邮件,password_hash,password_salt

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

在方法ENCRYPT_PASSWORD,又是怎样的变量密码访问?是一样self.password(对象变种),并且是本不一样@password? (为什么?)

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?)

在实际的加密程序,我调用self.password_salt。我注意到,我可以简单地输入password_salt(不涉及个体经营),它不工作。为什么不呢?这是为什么不同@password_salt?

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?

抱歉,如果这遇到如noobish,我已经花了好几个小时在这个扑远,我努力理解这一点。

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),这是一样的 self.password 。 ActiveRecord的定义的方法,而不是实例变量访问东西相关的数据库。这就是为什么你不能用 @密码访问它。

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)你需要使用 self.password_salt = ,否则你会被分配一个局部变量,而不是做一个方法调用。

2) You need to use self.password_salt= because otherwise you'd be assigning a local variable, not doing a method call.

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

PS: Callbacks are only method calls on your object. The only difference is that Rails calls them for you, not yourself.

这篇关于活动记录回调。他们怎么能够访问变量/范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆