Validate uniqueness of in association

前端 未结 4 1099
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 12:46

Given the following classes:

class Candidate
  has_many :applications
  has_many :companies, :through => :job_offers
end

class JobOffer
  belongs_to :company         


        
4条回答
  •  广开言路
    2021-02-05 13:29

    For anyone finding this today. The answer is to check when there are pre-existing (prevents multiple) & skip when the application itself is switching.

    def validate_uniqueness_of_candidate_within_company
      pre_existing = Application.includes(:candidate).includes(job_offer: :company).
        where(companies: { id: self.company.id }).
        where(candidates: { id: self.candidate.id })
    
      if pre_existing.present? && (!pre_existing.map(&:id).include? self.id)
        errors.add(:job_offer_id, "...")
      end
    end
    

提交回复
热议问题