Skip to content

Commit

Permalink
Implement find_in_batches without with_scope [#2227 state:resolved]
Browse files Browse the repository at this point in the history
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
libc authored and lifo committed Apr 15, 2010
1 parent b8b568e commit 18ba648
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
17 changes: 8 additions & 9 deletions activerecord/lib/active_record/batches.rb
Expand Up @@ -59,19 +59,18 @@ def find_in_batches(options = {})
start = options.delete(:start).to_i
batch_size = options.delete(:batch_size) || 1000

with_scope(:find => options.merge(:order => batch_order, :limit => batch_size)) do
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ])
proxy = scoped(options.merge(:order => batch_order, :limit => batch_size))
records = proxy.find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ])

while records.any?
yield records
while records.any?
yield records

break if records.size < batch_size
records = find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ])
end
break if records.size < batch_size
records = proxy.find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ])
end
end


private
def batch_order
"#{table_name}.#{primary_key} ASC"
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/batches_test.rb
Expand Up @@ -58,4 +58,10 @@ def test_find_in_batches_shouldnt_excute_query_unless_needed
Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch }
end
end

def test_find_in_batches_doesnt_clog_conditions
Post.find_in_batches(:conditions => {:id => posts(:welcome).id}) do
assert_nothing_raised { Post.find(posts(:thinking).id) }
end
end
end

0 comments on commit 18ba648

Please sign in to comment.