title: Validate uniqueness of in association
body: <p>Given the following classes:</p>
  
  <pre><code>class Candidate
    has_many :applications
    has_many :companies, :through =&gt; :job_offers
  end
  
  class JobOffer
    belongs_to :company
  end
  
  class Application
    belongs_to :candidate
    belongs_to :job_offer
  end
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/dsBN8.png" alt="enter image description here"></p>
  
  <p>How can I validate the previous statement (in the image) on Rails?</p>
  
  <p>Adding the following validation on Application won't work when updating:</p>
  
  <pre><code>def validate_uniqueness_of_candidate_within_company
    errors.add(:job_offer_id, "...") if candidate.companies.include?(company)
  end
  </code></pre>
  
  <p>Cause when trying to change the application to a different JobOffer of the same company candidate.companies will return that company.</p>
  
  <p>I also tried doing something like this on Application:</p>
  
  <pre><code>validates_uniqueness_of :user_id, :scope =&gt; {:job_offer =&gt; :company_id}
  </code></pre>
  
  <p>But it didn't work either.
  Any ideas to solve this without having to use 10 lines of crappy code?</p>