Validate uniqueness of in association

前端 未结 4 1101
被撕碎了的回忆
被撕碎了的回忆 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:33

    As the image points out, a candidate and a job offer will have many applications & a candidate can only apply to one job offer per company. So, validating uniqueness of candidate scoped to a job offer in application might do.

    class Candidate
      has_many :applications
      has_many :job_offers, :through => :applications
    end
    
    class JobOffer
      belongs_to :company
      has_many :applications
      has_many :candidates, :through => :applications
    end
    
    class Application
      belongs_to :candidate
      belongs_to :job_offer
    
      validates_uniqueness_of :candidate_id, :scope => :job_offer_id
    end
    

    This will prevent an application to be associated to the same candidate for the same job offer. The candidate can apply to other job offers, right?

    And as pointed out by @ez., renaming application to something appropriate is better.

    Hope this helps.

提交回复
热议问题