Is it possible to group validation?

Posted by lambdabutz on Stack Overflow See other posts from Stack Overflow or by lambdabutz
Published on 2010-06-10T21:10:21Z Indexed on 2010/06/10 21:12 UTC
Read the original article Hit count: 261

I am using a lot of my own validation methods to compare the data from one association to the other. I've noticed that I'm constantly checking that my associations aren't nil before trying to call anything on them, but I am also validating their presence, and so I feel that my nil checks are redundant. Here's an example:

class House < ActiveRecord::Base
  has_one :enterance, :class => Door
  has_one :exit, :class => Door

  validates_presence_of :enterance, :exit

  validate :not_a_fire_hazard
  def not_a_fire_hazard
    if enterance && exit && enterance.location != exit.location
      errors.add_to_base('If there is a fire you will most likely die')
      return false
    end
  end
end

I feel like I am repeating myself by checking the existence of enterance and exit within my own validation.

Is there a more "The Rails Way" to do this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validation