带有验证不工作存在的自定义消息 [英] Custom message with validates presence of not working
问题描述
我的 User
模型包含以下内容:
My User
model contains the following:
validates :password_digest, :presence => true, :message => "The password has to be 6 or more characters long"
def password=(password)
self.password_digest = BCrypt::Password.create(password) if password.length >= 6
end
问题是 validates
中的 message
不起作用.我收到一个 Unknown validator: 'MessageValidator'
错误.我假设 presence
验证的工作方式是它只会检查 password_digest
是否为 nil
,它会有 密码
的长度小于 6.我想要一个优雅的解决方案,就像我尝试的那样.我已经以一种方式解决了这个问题,但我真的很感激能理解为什么我正在尝试的方法不起作用,以及有没有办法让它起作用.
The issue is that the message
in the validates
isn't working. I get a Unknown validator: 'MessageValidator'
error. I assumed the way the presence
validation worked was that it would just check if the password_digest
was nil
, which it would be had the password
had a length less than 6. I want a solution that is elegant, like what I attempted. I have solved this one way, but I would really appreciate an understanding as to why what I'm trying isn't working, and is there a way to make it work.
我的工作是:
validate do |user|
user.errors['password'] = "can't be less than 6 characters" if user.password_digest.nil?
end
推荐答案
这是由于 validates
方法的工作方式造成的.当您指定 :message
作为传递给 validates
的哈希键时,它假定您正在查找 MessageValidator
.
This is due to how the validates
method works. It assumes that you're looking for the MessageValidator
when you specify :message
as a key in the hash passed to validates
.
这可以通过如下重构查询来解决:
This can be solved by reconstructing the query as follows:
validates :password_digest, :presence => { :message => "The password has to be 6 or more characters long" }
这篇关于带有验证不工作存在的自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!