Rails model.valid?冲洗自定义错误并错误地返回true [英] Rails model.valid? flushing custom errors and falsely returning true

查看:79
本文介绍了Rails model.valid?冲洗自定义错误并错误地返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的User模型的实例添加自定义错误,但是何时调用有效?

I am trying to add a custom error to an instance of my User model, but when I call valid? it is wiping the custom errors and returning true.

[99] pry(main)> u.email = "test@test.com"
"test@test.com"

[100] pry(main)> u.status = 1
1

[101] pry(main)> u.valid?
true

[102] pry(main)> u.errors.add(:status, "must be YES or NO")
[
    [0] "must be YES or NO"
]

[103] pry(main)> u.errors
#<ActiveModel::Errors:[...]@messages={:status=>["must be YES or NO"]}>

[104] pry(main)> u.valid?
true

[105] pry(main)> u.errors
#<ActiveModel::Errors:[...]@messages={}>

如果我从内部使用 validate 方法模型,然后就可以使用,但是此特定的验证是通过其他方法(需要传递参数)中添加的:

If I use the validate method from within the model, then it works, but this specific validation is being added from within a different method (which requires params to be passed):

User

def do_something_with(arg1, arg2)
  errors.add(:field, "etc") if arg1 != arg2
end

由于上述原因,user.valid吗?

Because of the above, user.valid? is returning true even when that error is added to the instance.

推荐答案

在ActiveModel中,有效吗?的定义如下:

In ActiveModel, valid? is defined as following:

def valid?(context = nil)
  current_context, self.validation_context = validation_context, context
  errors.clear
  run_validations!
ensure
  self.validation_context = current_context
end

因此存在错误已清除。您必须将所有自定义验证放入某些 validate 回调中。像这样:

So existing errors are cleared is expected. You have to put all your custom validations into some validate callbacks. Like this:

validate :check_status

def check_status
  errors.add(:status, "must be YES or NO") unless ['YES', 'NO'].include?(status)
end

这篇关于Rails model.valid?冲洗自定义错误并错误地返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆