Class: ActiveRecord::Errors

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/gems/activerecord-2.2.2/lib/active_record/validations.rb

Overview

Active Record validation is reported to and from this object, which is used by Base#save to determine whether the object is in a valid state to be saved. See usage example in Validations.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base) ⇒ Errors

:nodoc:



29
30
31
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 29

def initialize(base) # :nodoc:
  @base, @errors = base, {}
end

Class Method Details

.default_error_messagesObject



23
24
25
26
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 23

def default_error_messages
  ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
  I18n.translate 'activerecord.errors.messages'
end

Instance Method Details

#add(attribute, message = nil, options = {}) ⇒ Object

Adds an error message (messsage) to the attribute, which will be returned on a call to on(attribute) for the same attribute and ensure that this error object returns false when asked if empty?. More than one error can be added to the same attribute in which case an array will be returned on a call to on(attribute). If no messsage is supplied, :invalid is assumed. If message is a Symbol, it will be translated, using the appropriate scope (see translate_error).



46
47
48
49
50
51
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 46

def add(attribute, message = nil, options = {})
  message ||= :invalid
  message = generate_message(attribute, message, options) if message.is_a?(Symbol)
  @errors[attribute.to_s] ||= []
  @errors[attribute.to_s] << message
end

#add_on_blank(attributes, custom_message = nil) ⇒ Object

Will add an error message to each of the attributes in attributes that is blank (using Object#blank?).



63
64
65
66
67
68
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 63

def add_on_blank(attributes, custom_message = nil)
  for attr in [attributes].flatten
    value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
    add(attr, :blank, :default => custom_message) if value.blank?
  end
end

#add_on_empty(attributes, custom_message = nil) ⇒ Object

Will add an error message to each of the attributes in attributes that is empty.



54
55
56
57
58
59
60
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 54

def add_on_empty(attributes, custom_message = nil)
  for attr in [attributes].flatten
    value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
    is_empty = value.respond_to?(:empty?) ? value.empty? : false
    add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
  end
end

#add_to_base(msg) ⇒ Object

Adds an error to the base object instead of any particular attribute. This is used to report errors that don’t tie to any specific attribute, but rather to the object as a whole. These error messages don’t get prepended with any field name when iterating with each_full, so they should be complete sentences.



37
38
39
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 37

def add_to_base(msg)
  add(:base, msg)
end

#clearObject

Removes all errors that have been added.



221
222
223
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 221

def clear
  @errors = {}
end

#eachObject

Yields each attribute and associated message per error added.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
# => name - is too short (minimum is 5 characters)
#    name - can't be blank
#    address - can't be blank


165
166
167
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 165

def each
  @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
end

#each_fullObject

Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned through iteration as “First name can’t be empty”.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.each_full{|msg| puts msg }
# => Name is too short (minimum is 5 characters)
#    Name can't be blank
#    Address can't be blank


182
183
184
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 182

def each_full
  full_messages.each { |msg| yield msg }
end

#empty?Boolean

Returns true if no errors have been added.

Returns:

  • (Boolean)


216
217
218
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 216

def empty?
  @errors.empty?
end

#full_messages(options = {}) ⇒ Object

Returns all the full error messages in an array.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.full_messages # =>
  ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 196

def full_messages(options = {})
  full_messages = []

  @errors.each_key do |attr|
    @errors[attr].each do |message|
      next unless message

      if attr == "base"
        full_messages << message
      else
        #key = :"activerecord.att.#{@base.class.name.underscore.to_sym}.#{attr}" 
        attr_name = @base.class.human_attribute_name(attr)
        full_messages << attr_name + ' ' + message
      end
    end
  end
  full_messages
end

#generate_message(attribute, message = :invalid, options = {}) ⇒ Object

Translates an error message in it’s default scope (activerecord.errrors.messages). Error messages are first looked up in models.MODEL.attributes.ATTRIBUTE.MESSAGE, if it’s not there, it’s looked up in models.MODEL.MESSAGE and if that is not there it returns the translation of the default message (e.g. activerecord.errors.messages.MESSAGE). The translated model name, translated attribute name and the value are available for interpolation.

When using inheritence in your models, it will check all the inherited models too, but only if the model itself hasn’t been found. Say you have class Admin < User; end and you wanted the translation for the :blank error message for the title attribute, it looks for these translations:

<ol> <li>activerecord.errors.models.admin.attributes.title.blank</li> <li>activerecord.errors.models.admin.blank</li> <li>activerecord.errors.models.user.attributes.title.blank</li> <li>activerecord.errors.models.user.blank</li> <li>activerecord.errors.messages.blank</li> <li>any default you provided through the options hash (in the activerecord.errors scope)</li> </ol>



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 88

def generate_message(attribute, message = :invalid, options = {})

  message, options[:default] = options[:default], message if options[:default].is_a?(Symbol)

  defaults = @base.class.self_and_descendents_from_active_record.map do |klass| 
    [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}", 
      :"models.#{klass.name.underscore}.#{message}" ]
  end
  
  defaults << options.delete(:default)
  defaults = defaults.compact.flatten << :"messages.#{message}"

  key = defaults.shift
  value = @base.respond_to?(attribute) ? @base.send(attribute) : nil

  options = { :default => defaults,
    :model => @base.class.human_name,
    :attribute => @base.class.human_attribute_name(attribute.to_s),
    :value => value,
    :scope => [:activerecord, :errors]
  }.merge(options)

  I18n.translate(key, options)
end

#invalid?(attribute) ⇒ Boolean

Returns true if the specified attribute has errors associated with it.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.invalid?(:name)      # => true
company.errors.invalid?(:address)   # => false

Returns:

  • (Boolean)


123
124
125
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 123

def invalid?(attribute)
  !@errors[attribute.to_s].nil?
end

#on(attribute) ⇒ Object Also known as: []

Returns nil, if no errors are associated with the specified attribute. Returns the error message, if one error is associated with the specified attribute. Returns an array of error messages, if more than one error is associated with the specified attribute.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
company.errors.on(:email)     # => "can't be blank"
company.errors.on(:address)   # => nil


140
141
142
143
144
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 140

def on(attribute)
  errors = @errors[attribute.to_s]
  return nil if errors.nil?
  errors.size == 1 ? errors.first : errors
end

#on_baseObject

Returns errors assigned to the base object through add_to_base according to the normal rules of on(attribute).



149
150
151
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 149

def on_base
  on(:base)
end

#sizeObject Also known as: count, length

Returns the total number of errors added. Two errors added to the same attribute will be counted as such.



226
227
228
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 226

def size
  @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
end

#to_xml(options = {}) ⇒ Object

Returns an XML representation of this error object.

class Company < ActiveRecord::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.to_xml
# =>  <?xml version="1.0" encoding="UTF-8"?>
#     <errors>
#       <error>Name is too short (minimum is 5 characters)</error>
#       <error>Name can't be blank</error>
#       <error>Address can't be blank</error>
#     </errors>


248
249
250
251
252
253
254
255
256
257
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 248

def to_xml(options={})
  options[:root] ||= "errors"
  options[:indent] ||= 2
  options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])

  options[:builder].instruct! unless options.delete(:skip_instruct)
  options[:builder].errors do |e|
    full_messages.each { |msg| e.error(msg) }
  end
end