0

我正在尝试通过一次捕获来验证模型中某些字段的唯一性 - 如果记录具有某种共享关系,则不应引发错误。举例来说,这就是我的意思:

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

如果我使用validates_uniqueness_of :comments, :scope => :category_id,它将产生与我正在尝试做的完全相反的效果。有什么简单的方法可以做到这一点吗?谢谢。

4

1 回答 1

4

您需要自定义验证方法,如下所示:

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
于 2010-04-27T12:56:03.923 回答