0

モデル内のいくつかのフィールドの一意性を 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と、私がやろうとしていることとは正反対の効果が得られます。これを行う簡単な方法はありますか?ありがとう。

4

1 に答える 1

4

次のようなカスタム検証メソッドが必要です。

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
于 2010-04-27T12:56:03.923 に答える