简体   繁体   English

在Rails中保存模型中的记录之前,执行检查重复项的功能

[英]Performing a function to check for duplicates before saving the record in the model in Rails

This is what I have in my model. 这就是我的模型中的内容。 I want to check for duplicate records and I cant just use a unique index for a field since the contacts are unique per job) I am unable to do this using the following code. 我想检查重复记录,我不能只为字段使用唯一索引,因为每个作业的联系人是唯一的)我无法使用以下代码执行此操作。 Am I doing it wrong? 我做错了吗? Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

before_save :check_for_duplicates?

def check_for_duplicates?
  JobsPeople.find(:all, :conditions => ["job_id = ? and contact_id = ?", self.job_id, self.contact_id])
end

I believe this should do what you want 我相信这应该做你想要的

class JobsPeople
  validates_uniqueness_of :contact_id, scope: :job_id
end

Callbacks don't do anything more than run the code you tell them to run. 回调除了运行您告诉他们运行的代码之外,不会做任何事情。 If you want to prevent something from executing you have two options, use a validation or raise an error. 如果要阻止执行某些操作,则有两个选项,请使用验证或引发错误。

In your current code you could check if that query you ran returns anything, and then raise an error if it does. 在您当前的代码中,您可以检查您运行的查询是否返回任何内容,然后如果出现则引发错误。 The error will bubble up to the transaction that is wrapping the save and trigger a rollback, then propagate the error into your code where you can handle it if you want. 该错误将冒泡到包装保存并触发回滚的事务,然后将错误传播到您可以根据需要处理它的代码中。

before_save :check_for_duplicates?

def check_for_duplicates?
  if JobsPeople.find(:all, :conditions => ["job_id = ? and contact_id = ?", self.job_id, self.contact_id]).any?
    raise 'some error'
  end
end

Although there is already a built-in uniqueness validator that handles this situation 虽然已经有一个内置的唯一性验证器来处理这种情况

validates :job_id, :uniquness => {:scope => :contact_id, :message => 'must be unique per contact}

Of course this should still be backed up with a composite unique index in the database as there is a potential race condition, the likelihood of which depends largely on the behavior of your application. 当然,由于存在潜在的竞争条件,因此仍应使用数据库中的复合唯一索引进行备份,其可能性很大程度上取决于应用程序的行为。

# in a migration

add_index :table_name, [:job_id, :contact_id], :unique => true, :name => 'index_job_id_and_contact_id_on_table_name'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM