0
我試圖驗證我的模型中的一個字段的唯一性與一個捕獲 - 它不應該提出一個錯誤,如果記錄有一些共享關係。例如起見,這裏就是我的意思:Rails的 - validates_uniqueness_of模型字段與以下相反:範圍
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
,它就會有什麼,我試圖做完全相反的效果。任何簡單的方法來做到這一點?謝謝。