diff --git a/activerecord/lib/active_record/batches.rb b/activerecord/lib/active_record/batches.rb index 5a6cecd..cff0f9a 100644 --- a/activerecord/lib/active_record/batches.rb +++ b/activerecord/lib/active_record/batches.rb @@ -58,16 +58,20 @@ module ActiveRecord start = options.delete(:start).to_i batch_size = options.delete(:batch_size) || 1000 + conditions = options.delete(:conditions) - with_scope(:find => options.merge(:order => batch_order, :limit => batch_size)) do - records = find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ]) + options = { :order => batch_order, :limit => batch_size }.merge(options) + + records = find( :all, + options.merge( :conditions => merge_conditions( + [ "#{table_name}.#{primary_key} >= ?", start ], conditions ) ) ) - while records.any? - yield records - - break if records.size < batch_size - records = find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ]) - end + while records.any? + yield records + break if records.size < batch_size + records = find( :all, + options.merge( :conditions => merge_conditions( + [ "#{table_name}.#{primary_key} > ?", records.last.id ], conditions ) ) ) end end diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index 5009a90..efe45e9 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -28,6 +28,13 @@ class EachTest < ActiveRecord::TestCase Post.find_each(:limit => 1) { |post| post } end end + + def test_find_in_batches_shouldnt_override_conditions_inside_block + Post.find_each(:conditions => ["author_id = 1"]) do |post| + @post_count = Post.count + end + assert_equal @post_count, Post.count + end def test_find_in_batches_should_return_batches assert_queries(Post.count + 1) do