From 850b3ca4779da201d4805a12fe29d9d9a491739e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 29 Apr 2011 11:01:59 -0700 Subject: supporting nil when passed in as an IN clause --- .../lib/active_record/relation/predicate_builder.rb | 13 ++++++++++++- activerecord/test/cases/finder_test.rb | 7 ++++--- 2 files changed, 16 insertions(+), 4 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 982b3d7e9f..2814771002 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -25,7 +25,18 @@ module ActiveRecord values = value.to_a.map { |x| x.is_a?(ActiveRecord::Base) ? x.id : x } - attribute.in(values) + + if values.include?(nil) + values = values.compact + if values.empty? + attribute.eq nil + else + attribute.in(values.compact).or attribute.eq(nil) + end + else + attribute.in(values) + end + when Range, Arel::Relation attribute.in(value) when ActiveRecord::Base diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 9b6363902e..be4ba18555 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -1045,7 +1045,7 @@ class FinderTest < ActiveRecord::TestCase :order => ' author_addresses_authors.id DESC ', :limit => 3).size end - def test_find_with_nil_inside_set_passed_for_attribute + def test_find_with_nil_inside_set_passed_for_one_attribute client_of = Company.find( :all, :conditions => { @@ -1054,7 +1054,8 @@ class FinderTest < ActiveRecord::TestCase :order => 'client_of DESC' ).map { |x| x.client_of } - assert_equal [2, 1, nil], client_of + assert client_of.include?(nil) + assert_equal [2, 1].sort, client_of.compact.sort end def test_find_with_nil_inside_set_passed_for_attribute @@ -1064,7 +1065,7 @@ class FinderTest < ActiveRecord::TestCase :order => 'client_of DESC' ).map { |x| x.client_of } - assert_equal [nil], client_of + assert_equal [], client_of.compact end def test_with_limiting_with_custom_select -- cgit v1.2.3