I have two model as follows
class User < ActiveRecord::Base
validates_associated :account
end
class Account < ActiveRecord::Base
belongs_to :user
I ran into the same issue... I want to validate the associated objects, and have the valid?
method return false, but not add a (superfluous) message like 'Account invalid'. I just want the account validation messages to appear next to the account fields.
The only way I found to accomplish this is to override run_validations!
, like below. In this example, the association is has_many :contacts
:
def run_validations!
valid = super
contacts.each do |contact|
valid = false unless contact.valid?(validation_context)
end
valid
end
Don't use valid &&= contacts.all? ...
because that will prevent the validation on the contacts if the base class is already invalid, and will stop iteration if one of the contacts fails validation.
Perhaps it's an idea to generalize this into some Concern module, but I needed it only once.