Ruby on Rails:errors.add_to_base 与 errors.add
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/706533/
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
Ruby on Rails: errors.add_to_base vs. errors.add
提问by Tony
I have read that errors.add_to_base should be used for errors associated with the object and not a specific attribute. I am having trouble conceptualizing what this means. Could someone provide an example of when I would want to use each?
我已经读过,errors.add_to_base 应该用于与对象相关的错误,而不是特定的属性。我在概念化这意味着什么时遇到了麻烦。有人可以提供一个我何时想要使用每个的例子吗?
For example, I have a Band model and each Band has a Genre. When I validate the presence of a genre, if the genre is missing should the error be added to the base?
例如,我有一个乐队模型,每个乐队都有一个流派。当我验证流派的存在时,如果流派丢失,是否应该将错误添加到基础中?
The more examples the better
例子越多越好
Thank you!
谢谢!
采纳答案by MarkusQ
A missing genre would be a field error. A base error would be something like an exact duplicate of an existing record, where the problem wasn't tied to any specific field but rather to the record as a whole (or at lest to some combination of fields).
缺少的流派将是字段错误。基本错误类似于现有记录的完全重复,其中问题与任何特定字段无关,而是与整个记录有关(或至少与某些字段组合有关)。
回答by GSP
It's worth noting (since this shows up in the search engines, which is how I found it) that this is deprecated. The Rails 3 way of doing it is:
值得注意的是(因为这会出现在搜索引擎中,这就是我发现它的方式)这已被弃用。Rails 3 的做法是:
errors[:base] << "Error message"
or
或者
errors.add(:base, "Error message")
http://apidock.com/rails/ActiveRecord/Errors/add_to_base
http://apidock.com/rails/v3.2.8/ActiveModel/Errors/add
http://apidock.com/rails/ActiveRecord/Errors/add_to_base
http://apidock.com/rails/v3.2.8/ActiveModel/Errors/add
回答by Jon Kern
In this example, you can see field validation (team must be chosen). And you can see a class/base level validation. For example, you required at least one method of contact, a phone or an email:
在此示例中,您可以看到字段验证(必须选择团队)。您可以看到类/基础级别的验证。例如,您至少需要一种联系方式、电话或电子邮件:
class Registrant
include MongoMapper::Document
# Attributes ::::::::::::::::::::::::::::::::::::::::::::::::::::::
key :name, String, :required => true
key :email, String
key :phone, String
# Associations :::::::::::::::::::::::::::::::::::::::::::::::::::::
key :team_id, ObjectId
belongs_to :team
...
# Validations :::::::::::::::::::::::::::::::::::::::::::::::::::::
validate :validate_team_selection
validate :validate_contact_method
...
private
def validate_contact_method
# one or the other must be provided
if phone.empty? and email.empty?
errors.add_to_base("At least one form of contact must be entered: phone or email" )
end
end
def validate_team_selection
if registration_setup.require_team_at_signup
if team_id.nil?
errors.add(:team, "must be selected" )
end
end
end
end

