2010-04-27 47 views
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,它就會有什麼,我試圖做完全相反的效果。任何簡單的方法來做到這一點?謝謝。

回答

3

你需要自定義的驗證方法,像這樣:

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