Module: ActiveRecord::Validations::ClassMethods

Defined in:
lib/mir_utility.rb

Instance Method Summary collapse

Instance Method Details

#validates_associated(*associations) ⇒ Object

Overrides validates associates. We do this to allow more better error messages to bubble up from associated models. Adapted from thread at pivotallabs.com/users/nick/blog/articles/359-alias-method-chain-validates-associated-informative-error-message



112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/mir_utility.rb', line 112

def validates_associated(*associations)
  # These configuration lines are required if your going to use any conditionals with the validates associated - Rails 2.2.2 safe!
  configuration = { :message => I18n.translate('activerecord.errors.messages'), :on => :save }
  configuration.update(associations.extract_options!)
  associations.each do |association|
    class_eval do
      validates_each(associations,configuration) do |record, associate_name, value|
        associates = record.send(associate_name)
        associates = [associates] unless associates.respond_to?('each')
        associates.each{ |associate| associate.errors.each{ |key, value2| record.errors.add("", "#{value2}") } if associate && !associate.valid? }
      end
    end
  end
end