Given the following classes:
class Candidate
has_many :applications
has_many :companies, :through => :job_offers
end
class JobOffer
belongs_to :company
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