我正在尝试通过一次捕获来验证模型中某些字段的唯一性 - 如果记录具有某种共享关系,则不应引发错误。举例来说,这就是我的意思:
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
,它将产生与我正在尝试做的完全相反的效果。有什么简单的方法可以做到这一点吗?谢谢。