Custom message with validates presence of not working

被刻印的时光 ゝ 提交于 2019-12-13 16:30:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!