Ruby on rails Rails模型:在保存{self.password=password.strip}之前vs.在保存{password.strip!}之前
在我的用户模型中,我有几行代码可以从用户的电子邮件和密码中去掉前导/尾随空格。原始代码如下所示:Ruby on rails Rails模型:在保存{self.password=password.strip}之前vs.在保存{password.strip!}之前,ruby-on-rails,before-save,Ruby On Rails,Before Save,在我的用户模型中,我有几行代码可以从用户的电子邮件和密码中去掉前导/尾随空格。原始代码如下所示: before_save {self.email = email.strip} before_save {self.password = password.strip} before_save {self.password_confirmation = password_confirmation.strip} 这通过了我的测试: test "password entry should ignore
before_save {self.email = email.strip}
before_save {self.password = password.strip}
before_save {self.password_confirmation = password_confirmation.strip}
这通过了我的测试:
test "password entry should ignore leading/tailing whitespace" do
@user = User.create(name: "M", email: " foo@bar.com",
password: " password", password_confirmation: " password")
assert @user.authenticate("password")
assert_not @user.authenticate(" password")
end
现在我试着重新考虑:
before_save {email.strip!}
before_save {password.strip!}
before_save {password_confirmation.strip!}
这对我的电子邮件测试很有效,但它破坏了上面的密码测试。所以,问题是,原始版本与重新分解的代码有什么不同?您不能使用
password.strip
因为实际上没有像password
这样的字段-它是一个setterpassword=
来生成和存储密码散列。我想我明白了。因此,虽然@password有一个reader方法,但是密码被散列的代码只出现在setter方法中。这样我就可以调用self.password.strip!,但它不会将结果传递给哈希函数。它会更改实例变量,但更改不会使其进入数据库。原始版本确实有效,因为它使用setter方法。听起来对吗?