validates_uniqueness_of...and unless
What's the proper way to write?
validates_uniqueness_of :a, :sc开发者_如何学运维ope => [:b, :c], :unless => !d.nil?
It very simple:
validates_uniqueness_of :a, :scope => [:b, :c], :unless => :d
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.
精彩评论