Ruby-on-rails 如何将自定义错误添加到用户错误集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5320934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add custom errors to the User errors collection?
提问by Blankman
How can I add errors to the Usermodel manually?
如何User手动向模型添加错误?
Is it just @user.errors << "some text goes here"?
只是@user.errors << "some text goes here"吗?
回答by Ashish
回答by Jason Axelson
WARNING
警告
If you just add errors in a separate method (not in a validation), then by default when you call .valid?or .savethose errors will be automatically cleared. So you may want to use validation contextsinstead.
如果您只是在单独的方法中添加错误(而不是在验证中),那么默认情况下,当您调用.valid?或.save这些错误将被自动清除。因此,您可能希望改用验证上下文。
回答by Mike Lewis
回答by mmike
try this:
尝试这个:
errors.add(:base, "#{user.full_name} has errors here!")

