alias_method_chain :validates_associated, :informative_error_message

January 4, 2008 Pivotal Labs

I dislike the vague error message produced by validates_associated.

class User
  validates_associated :profile
  delegate ..., :to => :profile
end

I see the following error message: profile is invalid. But WHY was the profile invalid? The validation errors from the profile should bubble up to the user. So,

module ActiveRecord::Validations::ClassMethods
  def validates_associated(association, options = {})
    class_eval do
      validates_each(association) do |record, associate_name, value|
        associate = record.send(associate_name)
        if associate && !associate.valid?
          associate.errors.each do |key, value|
            record.errors.add(key, value)
          end
        end
      end
    end
  end
end

Now we see:

Music tastes can't be blank

Eh, voila!

About the Author

Biography

More Content by Pivotal Labs
Previous
Helpful Named-Route Error Messages
Helpful Named-Route Error Messages

Sometimes I call a named route incorrectly: edit_user_project_path(project). And I get an illegible error m...

Next
Kombucha anyone?
Kombucha anyone?

As geeks we like science experiments. As San Franciscans (mostly) we like anything novel, particularly i...