keruilin
keruilin

Reputation: 17552

validates_uniqueness_of...and unless

What's the proper way to write?

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

Upvotes: 3

Views: 1503

Answers (2)

Eimantas
Eimantas

Reputation: 49354

It very simple:

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

Upvotes: 2

Ian Lesperance
Ian Lesperance

Reputation: 5139

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.

Upvotes: 2

Related Questions