You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

Y U No Validate Me?

June 20th, 2013

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)
    super
    my_model.errors.each{ |k, v| self.errors[k] << v } if my_model.invalid?
    errors.empty?
  end

Ah, sweet validation.

Entry Filed under: Professional,Ruby on Rails

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>