lib/sequel/plugins/validation_helpers.rb in sequel-3.6.0 vs lib/sequel/plugins/validation_helpers.rb in sequel-3.7.0
- old
+ new
@@ -151,19 +151,24 @@
# This validation does not respect the :allow_* options that the other validations accept,
# since it can deal with a grouping of multiple attributes.
#
# Possible Options:
# * :message - The message to use (default: 'is already taken')
+ # * :only_if_modified - Only check the uniqueness if the object is new or
+ # one of the columns has been modified.
def validates_unique(*atts)
opts = default_validation_helpers_options(:unique)
if atts.last.is_a?(Hash)
opts = opts.merge(atts.pop)
end
message = validation_error_message(opts[:message])
atts.each do |a|
- ds = model.filter(Array(a).map{|x| [x, send(x)]})
+ arr = Array(a)
+ next if opts[:only_if_modified] && !new? && !arr.any?{|x| changed_columns.include?(x)}
+ ds = model.filter(arr.map{|x| [x, send(x)]})
ds = yield(ds) if block_given?
- errors.add(a, message) unless (new? ? ds : ds.exclude(pk_hash)).count == 0
+ ds = ds.exclude(pk_hash) unless new?
+ errors.add(a, message) unless ds.count == 0
end
end
private