7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# File 'lib/active_item/validations.rb', line 7
def validate_each(record, attribute, value)
return if value.nil? || value.to_s.empty?
conditions = { attribute => value }
if options[:scope]
Array(options[:scope]).each do |scope_attr|
conditions[scope_attr] = record.send(scope_attr)
end
end
existing = record.class.where(**conditions)
existing = existing.reject { |r| r.id == record.id } if record.id
existing = existing.select { |r| options[:conditions].call(r) } if options[:conditions]
record.errors.add(attribute, options[:message] || 'has already been taken') if existing.any?
end
|