views:

17

answers:

2

What's the proper way to write?

validates_uniqueness_of :a, :scope => [:b, :c], :unless => !d.nil?
+1  A: 

Just pass a Proc that returns true or false to the :if or :unless option:

validates_uniqueness_of :a, :scope => [:b, :c], :unless => Proc.new { |obj| !obj.d.nil? }
validates_uniqueness_of :a, :scope => [:b, :c], :if => Proc.new { |obj| obj.d.nil? }

(This assumes that d is a property or method of your model.)

Of course, this is not a perfect guarantee of uniqueness. By default there is a race condition that could allow duplicates. See the documentation for more information.

Ian
+1  A: 

It very simple:

validates_uniqueness_of :a, :scope => [:b, :c], :unless => :d
Eimantas