我正在关注 Michael Hartl 的 RoR 教程,它涵盖了密码加密的基础知识。这是当前的用户模型:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email,: password, :password_confirmation
email_regex = /^[A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/
#tests for valid email addresses.
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:length => {:maximum => 20, :minimum => 6},
:confirmation => true
before_save :encrypt_password
private
def encrypt_password
self.encrypted_password = encrypt(password)
end
def encrypt(string)
string
end
end
我之前发布了一个关于before_save
不起作用,事实证明我不小心所做的是将我的 encrypt_password 写为:
def encrypt_password
@encrypted_password = encrypt(password)
end
我知道如果 self.encrypted_password 设置了 crypto_password 属性,但为什么 @encrypted_password 不这样做呢?在对上一篇文章的回复中before_save
不工作 有人说,在方法以我最初编码的方式结束后,实例变量被“忘记”了——为什么会这样?有人可以解释一下 self 和 @ 的工作方式有何不同吗在上面代码的上下文中?
注意:我已经看过帖子了here https://stackoverflow.com/questions/1693243/instance-variable-self-vs and here https://stackoverflow.com/questions/4639271/ruby-self-vs,但他们都说“自我”正在呼唤attribute =
方法,我什至不明白该方法如何存在于此处,因为我从未创建过它或声明过 crypto_password w/attr_accessor
。所以我还是很困惑,而且这不是这些问题的重新发布。