Validates_uniqueness_of ... and if

What is the right way to write?

validates_uniqueness_of :a, :scope => [:b, :c], :unless => !d.nil?
+3
source share
2 answers

It is very simple:

validates_uniqueness_of :a, :scope => [:b, :c], :unless => :d
+2
source

Just pass Procthat returns true or false in the :ifor parameter :unless:

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? }

(Assumed to be da property or method of your model.)

Of course, this is not an ideal guarantee of uniqueness. By default, there is a race condition that can allow duplicates. For more information, see. In the documentation .

+2
source

Source: https://habr.com/ru/post/1752570/


All Articles