validates associated with model's error message

前端 未结 7 1498
孤独总比滥情好
孤独总比滥情好 2020-12-08 10:04

I have two model as follows

class User < ActiveRecord::Base
 validates_associated :account
end

class Account < ActiveRecord::Base

  belongs_to :user
         


        
相关标签:
7条回答
  • 2020-12-08 10:56

    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.

    0 讨论(0)
提交回复
热议问题