Ruby on Rails:errors.add_to_base vs. errors.add

我已经读了errors.add_to_base应该用于与对象相关的错误,而不是一个特定的属性。 我很难概念化这意味着什么。 有人可以提供一个什么时候我想要使用每个?

例如,我有一个乐队模型,每个乐队都有一个stream派。 当我validationstream派的存在时,如果stream派丢失,应该将错误添加到基地?

越多的例子越好

谢谢!

缺less的types将是一个字段错误。 一个基本的错误就像是一个现有logging的完全重复,这个问题不是绑定到任何特定的领域,而是整个logging(或者至less是某些字段的组合)。

值得注意的是(因为这在search引擎中出现,这是我如何find它),这已被弃用。 Rails 3的做法是:

errors[:base] << "Error message" 

要么

 errors.add(:base, "Error message") 

http://apidock.com/rails/ActiveRecord/Errors/add_to_base
http://apidock.com/rails/v3.2.8/ActiveModel/Errors/add

在这个例子中,你可以看到字段validation(必须select团队)。 你可以看到一个类/基本级别的validation。 例如,您至less需要一个联系方式,一个电话或一封电子邮件:

 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