From ad1a24f0e04ccff17df604c7781f4805ace2ec0f Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Sat, 9 Mar 2013 21:22:12 +0100 Subject: Uniqueness validation uses a proc to specify the `:conditions` option. This is a follow up to #5321 and follows the general direction in AR to make things lazy evaluated. --- activerecord/lib/active_record/validations/uniqueness.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'activerecord/lib/active_record/validations/uniqueness.rb') diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 1427189851..bf2aa2e959 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -2,6 +2,10 @@ module ActiveRecord module Validations class UniquenessValidator < ActiveModel::EachValidator # :nodoc: def initialize(options) + if options[:conditions] && !options[:conditions].respond_to?(:call) + raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \ + "Pass a callable instead: `conditions: -> { where('approved = ?', true) }`" + end super({ case_sensitive: true }.merge!(options)) end @@ -19,7 +23,7 @@ module ActiveRecord relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted? relation = scope_relation(record, table, relation) relation = finder_class.unscoped.where(relation) - relation.merge!(options[:conditions]) if options[:conditions] + relation = relation.merge(options[:conditions]) if options[:conditions] if relation.exists? error_options = options.except(:case_sensitive, :scope, :conditions) @@ -116,7 +120,7 @@ module ActiveRecord # of the title attribute: # # class Article < ActiveRecord::Base - # validates_uniqueness_of :title, conditions: where('status != ?', 'archived') + # validates_uniqueness_of :title, conditions: -> { where('status != ?', 'archived') } # end # # When the record is created, a check is performed to make sure that no @@ -132,7 +136,7 @@ module ActiveRecord # the uniqueness constraint. # * :conditions - Specify the conditions to be included as a # WHERE SQL fragment to limit the uniqueness constraint lookup - # (e.g. conditions: where('status = ?', 'active')). + # (e.g. conditions: -> { where('status = ?', 'active') }). # * :case_sensitive - Looks for an exact match. Ignored by # non-text columns (+true+ by default). # * :allow_nil - If set to +true+, skips this validation if the -- cgit v1.2.3