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

前端 未结 3 2016
失恋的感觉
失恋的感觉 2021-01-31 02:00

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. Cou

相关标签:
3条回答
  • 2021-01-31 02:31

    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
    
    0 讨论(0)
  • 2021-01-31 02:43

    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:

    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

    0 讨论(0)
  • 2021-01-31 02:49

    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).

    0 讨论(0)
提交回复
热议问题