2

I'm using contexts to invoke specific validations at different points in the model lifecycle:

model Address
    validates :city, presence: true
    validates :street, presence: true, on: :send_letter
end

incomplete_address = Address.new(city: 'Berlin')
incomplete_address.valid? # => true
incomplete_address.valid?(:send_letter) # => false

This works fine for the simple case above. But, as far as I can tell, the context is ignored for any associated objects:

model Address
    belongs_to :country
    validates :street, presence: true, on: :send_letter
    validates_associated :country
end

model Country
    has_many :addresses
    validates :iso_alpha_3, presence: true, size: 3, on: :send_letter
end

incomplete_address = Address.new(street: 'Oranienstr', country: Country.new(name: 'Germany', iso_alpha_3: 'Invalid iso code')

incomplete_address.valid? # => true
incomplete_address.valid?(:send_letter) # => true
incomplete_address.country.valid?(:send_letter) => false

Question: Is this expected behaviour, or is it a bug I'm hitting? Or am I making a conceptual mistake? What's the most elegant way to validate associated models under such circumstances?

2 Answers 2

5

I know this question is 3 years old but there is a slightly easier path now and an an even easier option on the horizon.

There is currently an outstanding PR that adds this functionality via a configuration option on the validates_associated call. In the meantime, you can add that version of AssociatedValidator as a separate validator (e.g. AssociatedPreservingContextValidator) and call validate_with AssociatedPreservingContextValidator, :country in `Address.

1

Is the expected behaviour, validators are executed only in the current model. You can achieve the desired result using a custom method validator.

You can find more informations here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.