开发者

Rails - validates_uniqueness_of model field with the inverse of :scope

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({开发者_JS百科 :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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜