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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:41:11  来源:igfitidea点击:

How to add custom errors to the User errors collection?

ruby-on-rails

提问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

 @user.errors.add(:email, "Not valid")

If you don't want to use any attributes, then in your model

如果您不想使用任何属性,则在您的模型中

 @user.errors[:base] << "This person is invalid because ..."

For details: link

详情:链接

回答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

Use the errors.add method

使用errors.add 方法

Example:

例子:

@user.errors.add(:name, "wasn't filled in")

回答by mmike

try this:

尝试这个:

errors.add(:base, "#{user.full_name} has errors here!")