views:

87

answers:

1

Hi - I'm trying to validate uniqueness of some field in my model with one catch - it shouldn't raise an error if records have some shared relation. For the sake of example, here's what I mean:

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

if I use validates_uniqueness_of :comments, :scope => :category_id, it'll have the exact opposite effect of what I'm trying to do. Any simple way to do this? thanks.

+2  A: 

You need custom validation method, something like this:

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
Voyta