在两个单独的列中验证一个属性的唯一性



我需要验证两个字段。

模型

:name
:original_url #(this cannot match any url or original_url)
:url #(this cannot match any url or original_url)

我可以单独验证每个

validates_uniqueness_of :name, scope: {:url, :original_url}

,但我无法弄清楚我如何确保两个领域。我也很关心性能(表具有2M记录)。字段是索引的,所以我希望这足够了。

知道最好的方法是什么?

做到这一点的最佳方法是在数据库级别和Rails模型中。我可以为您提供后者的帮助,希望有人也可以在如何通过SQL添加它。由于您没有指定名称:

,我将保留在"模型"上下文中

在您的型号中。RB文件:

validate :ensure_unique_for_both_cols
def ensure_unique_for_both_cols
  if self.original_url || self.url
    #Ensure no record matching this exists in either field
    unless Model.where("original_url = ? OR url = ?",self.original_url, self.url).empty?
       self.errors.add(:base, "The url must be unique!")
    end
  end     
end

感谢上面的bkunzi将我指向正确的曲目。

验证:suse_urls_unique

def ensure_urls_unique
  urls = [self.url, self.original_url].compact # To allow 'nil' to match
  if Job.where("original_url IN (?) OR ad_url IN (?)",urls, urls).where(name:self.name).where.not(id:self.id).exists?
    self.errors.add(:base, "The urls must be unique!")
  else
    return true
  end
end

值得注意的是。表现胜于empty?在大型样本集或可能获得比赛的地方。

相关内容

最新更新