问题
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
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.
What I got to work was:
validate do |user|
user.errors['password'] = "can't be less than 6 characters" if user.password_digest.nil?
end
回答1:
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" }
来源:https://stackoverflow.com/questions/18262704/custom-message-with-validates-presence-of-not-working