验证关联的唯一性 [英] Validate uniqueness of in association

查看:44
本文介绍了验证关联的唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类:

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

如何在 Rails 上验证之前的语句(在图像中)?

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

因为当尝试将申请更改为同一公司候选人的不同 JobOffer 时.公司将返回该公司.

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}

但也没有用.有什么想法可以解决这个问题而不必使用 10 行糟糕的代码?

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

推荐答案

可能有许多可接受的方法来解决您的问题,但我认为最重要的是您正在尝试对表强制执行唯一性约束t(直接)拥有所有属性(companyuser).我会将 company 信息反规范化到应用程序表(user_idjob_offer_idcompany_id)中,并且始终将其设置在 before_save 回调中以匹配 job_offercompany.然后你应该能够使用作用域唯一性验证:

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

这篇关于验证关联的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆