Module: ActiveRecord::Validations::ClassMethods
- Defined in:
- lib/active_record/validates_associated_record.rb
Instance Method Summary collapse
-
#validates_associated(*attr_names) ⇒ Object
This overwritten method will merge errors from associated record when it’s invalid.
Instance Method Details
#validates_associated(*attr_names) ⇒ Object
This overwritten method will merge errors from associated record when it’s invalid
Examples
class Person < ActiveRecord::Base
has_one :address
validates_presence_of :name
validates_associated_record :address
delegate :street, :street=, :city, :city=, :state, :state=,
:zip, :zip=, :to => :address
end
class Address < ActiveRecord::Base
validates_presence_of :street, :city, :state, :zip
end
joe = Person.new
joe.valid? # => false
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"
29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/active_record/validates_associated_record.rb', line 29 def validates_associated(*attr_names) configuration = { :on => :save } configuration.update(attr_names.) send(validation_method(configuration[:on]), configuration) do |record| attr_names.each do |attr_name| if associated_record = record.send(attr_name.to_sym) unless associated_record.valid? record.errors.merge(associated_record.errors) end end end end end |