モデル内のいくつかのフィールドの一意性を 1 つのキャッチで検証しようとしています。レコードに共有関係がある場合、エラーは発生しません。例として、ここに私が意味するものがあります:
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
と、私がやろうとしていることとは正反対の効果が得られます。これを行う簡単な方法はありますか?ありがとう。