Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate uniqueness of in association

Given the following classes:

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

class JobOffer
  belongs_to :company
end

class Application
  belongs_to :candidate
  belongs_to :job_offer
end

enter image description here

How can I validate the previous statement (in the image) on Rails?

Adding the following validation on Application won't work when updating:

def validate_uniqueness_of_candidate_within_company
  errors.add(:job_offer_id, "...") if candidate.companies.include?(company)
end

Cause when trying to change the application to a different JobOffer of the same company candidate.companies will return that company.

I also tried doing something like this on Application:

validates_uniqueness_of :user_id, :scope => {:job_offer => :company_id}

But it didn't work either. Any ideas to solve this without having to use 10 lines of crappy code?

like image 433
user1163964 Avatar asked Jan 22 '12 21:01

user1163964


1 Answers

There are likely many acceptable approaches to solve your issue but I think the bottom line is that you're trying to enforce a uniqueness constraint on the table that doesn't (directly) have all the attributes (both company AND user). I'd de-normalize the company info into the application table (user_id, job_offer_id, company_id) and always set it in a before_save callback to match the job_offer's company. Then you should be able to use the scoped uniqueness validation:

class JobApplication < ActiveRecord::Base
  belongs_to :user
  belongs_to :job_offer
  belongs_to :hiring_company, :class_name=>"Company", :foreign_key=>"company_id"

  before_save :set_hiring_company

  def set_hiring_company
   self.hiring_company = job_offer.hiring_company
  end

  validates_uniqueness_of :user_id, :scope => :company_id
end
like image 138
miked Avatar answered Oct 29 '22 05:10

miked