简体   繁体   English

Rails-带:scope倒数的validates_uniqueness_of模型字段

[英]Rails - validates_uniqueness_of model field with the inverse of :scope

I'm trying to validate uniqueness of some field in my model with one catch - it shouldn't raise an error if records have some shared relation. 我正在尝试通过一次验证来验证模型中某些字段的唯一性-如果记录具有某种共享关系,则不应引发错误。 For the sake of example, here's what I mean: 为了举例,这就是我的意思:

class Product < ActiveRecord::Base
  belongs_to :category  
end

class Category < ActiveRecord::Base
  has_many :products
end


>>> Category.create({ :name => 'Food' }) # id = 1
>>> Category.create({ :name => 'Clothing' }) # id = 2

>>> p1 = Product.new({ :name => 'Cheese', :category_id => 1, :comments => 'delicious' })
>>> p2 = Product.new({ :name => 'Bread', :category_id => 1, :comments => 'delicious' })
>>> p3 = Product.new({ :name => 'T-Shirt', :category_id => 2, :comments => 'delicious' })
>>> p1.save
>>> p2.save # should succeed - shares the same category as duplicate comment
>>> p3.save # should fail - comment is unique to category_id = 1

if I use validates_uniqueness_of :comments, :scope => :category_id , it'll have the exact opposite effect of what I'm trying to do. 如果我使用validates_uniqueness_of :comments, :scope => :category_id ,它将具有与我尝试执行的操作完全相反的效果。 Any simple way to do this? 有任何简单的方法吗? thanks. 谢谢。

You need custom validation method, something like this: 您需要自定义验证方法,如下所示:

validate :validate_comments

def validate_comments
  if Product.count(:conditions => ["comments = ? and category_id != ?", comments, category_id]) > 0
    errors.add_to_base("... Your error message")
  end
end

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

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