Class: ActiveRecord::Errors
- Inherits:
-
Object
- Object
- ActiveRecord::Errors
- Defined in:
- lib/active_record/errors.rb
Instance Method Summary collapse
-
#merge(errors, options = {}) ⇒ Object
Merges the errors from the passed in errors object onto this errors object.
Instance Method Details
#merge(errors, options = {}) ⇒ Object
Merges the errors from the passed in errors object onto this errors object.
Examples
class Person < ActiveRecord::Base
validates_presence_of :name
end
class Address < ActiveRecord::Base
validates_presence_of :street, :city, :state, :zip
end
joe = Person.new
joe.valid? # => false
address = Address.new
address.valid? # => false
joe.errors.merge address.errors
joe.errors.on(:name) # => "can't be blank"
joe.errors.on(:street) # => "can't be blank"
joe.errors.on(:city) # => "can't be blank"
joe.errors.on(:state) # => "can't be blank"
joe.errors.on(:zip) # => "can't be blank"
Options
* +only+ - can take a single field or an array of fields, it merges errors from the specified fields
* +except+ - can take a single field or an array of fields, it merges all errors except the on the fields specified
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/active_record/errors.rb', line 35 def merge(errors, ={}) fields_to_merge = if only=[:only] only elsif except=[:except] except = [except] unless except.is_a?(Array) except.map!(&:to_sym) errors.entries.map(&:first).select do |field| !except.include?(field.to_sym) end else errors.entries.map(&:first) end fields_to_merge = [fields_to_merge] unless fields_to_merge.is_a?(Array) fields_to_merge.map!(&:to_sym) errors.entries.each do |field, msg| add field, msg if fields_to_merge.include?(field.to_sym) end end |