我是Ruby语言和Rails的新手。我目前正在构建一些简单的用户注册流程。当我使用这些代码时Rails抛出: 没有从nil到字符串的隐式转换
这是原始代码:
require 'digest'
class User < ActiveRecord::Base
before_save :encrypt_password
protected
def encrypt_password
return if password.blank?
password = encrypt(password)
end
def encrypt(string)
Digest::SHA1.hexdigest(string)
end
end
但如果我将此行password = encrypt(password)
更改为self.password = encrypt(password)
,则此功能正常。我只是好奇,第一个代码出了什么问题?
答案 0 :(得分:3)
Ruby不允许将隐式self.
与person=
类型的方法一起使用
那是因为它认为你正在设置一个局部变量。所以它不依赖于自我。
您需要明确指定self.password =
。