Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating nested models with ActiveModel::Validations

My application uses plain Ruby classes with ActiveModel::Validations, without implementing ActiveRecord:

class Car
  include ::ActiveModel::Validations

  attr_accessor :engine
end

class Engine
  include ::ActiveModel::Validations

  attr_accessor :cylinders
  validates_presence_of :cylinders
end

I would like Car to check the nested attributes that are of ActiveModel::Validations, in this case engine.

car = Car.new
car.engine = Engine.new

car.engine.valid? # => false
car.valid?        # => true
                  # It should return 'false',
                  # because 'engine.cylinders' is 'nil'

What's the easiest way to get this behavior?

like image 340
David Elner Avatar asked Oct 19 '22 08:10

David Elner


1 Answers

One option is creating your own validation method, something like

class Car
  include ::ActiveModel::Validations

  attr_accessor :engine

  validate :engine_must_be_valid

  def engine_must_be_valid
    errors.add(:base, "Engine is not valid") unless engine.valid?
  end
end
like image 189
Aguardientico Avatar answered Nov 15 '22 10:11

Aguardientico