Y U No Validate Me?

Geek Mama 2015-12-22

I have a class that inherits from Active::Model that is encapsulating some logic from other models. Problem is, I’d really like my object to display validation errors. All of them.

There are attributes on my ActiveModel class, and then I need to validate attributes on the ActiveRecord classes that are being updated here as well.

Yeah, I’m pretty sure that I’m not the only one who initially thought that self.errors returns an array of errors. It doesn’t. It returns the Errors object.

If you want to add to your errors object, turns out you gotta get friendly with Validations too. They go hand in hand.

It’s in the valid? method where all the magic happens. Check this out:

  def valid?(context = nil)
    my_model.errors.each{ |k, v| self.errors[k] << v } if my_model.invalid?

Ah, sweet validation.