3

Let's say I have two models using Rails Single Table Inheritance. I can easily add validations in child model to make certain field required. But what if I want change validations making fields optional in Child model or have different criteria (like numericality)?

class Parent
  include Mongoid::Document
  field :name, type: String
  field :age, type: Integer
  validates :name, presence: true
  validates :age,   numericality: { greater_than_or_equal_to: 25 }
end
class Child < Parent
  # how can I make name optional in Child?  
  validates :age,   numericality: { less_than: 25 }
end

I can do with by creating custom validation methods and then overriding them in child class but I was hoping there was a way to do it just using default Rails validator format.

Dmitry Polyakovsky
  • 1,535
  • 11
  • 31

1 Answers1

5

You should be able to do something like this in Parent

validates :name, presence: true, unless: proc { |c| c.is_a? Child }

Not fantastic, but is pretty clean if you only have one subclass you want to override. I am sure there are other approaches

joem
  • 331
  • 1
  • 7