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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With