Conditional Validations in Rails

August 28th, 2007 by pyrat

The single table inheritance feature of rails is really useful. Today I needed to turn off validations in the extended model that were implemented in the base class.

I scratched my head for a while then realised its actually very simple.

class Page < ActiveRecord::Base

validates_presence_of :title, :slug,
:description, :if => :is_a_page?

private

def is_a_page?
self.class == ‘Page’
end

end

The above validation only takes place for the base class and not for classes that extend this. The beauty of STI being that the database stays pretty clean.

Leave a Reply