validation - Rails - validates_uniqueness_of model field with the inverse of :scope -


i'm trying validate uniqueness of field in model 1 catch - shouldn't raise error if records have shared relation. sake of example, here's 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 same category duplicate comment >>> p3.save # should fail - comment unique category_id = 1 

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

you need custom validation method, this:

validate :validate_comments  def validate_comments   if product.count(:conditions => ["comments = ? , category_id != ?", comments, category_id]) > 0     errors.add_to_base("... error message")   end end 

Comments

Popular posts from this blog

Delphi Wmi Query on a Remote Machine -