我正在尝试用一个catch来验证模型中某些字段的唯一性 - 如果记录有一些共享关系,它不应该引发错误。为了举例,这就是我的意思:
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
,它会产生与我正在尝试的完全相反的效果。有什么简单的方法吗?感谢。
答案 0 :(得分: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