Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:select with find_in_batches in rails

How can I include a :select clause with find_in_batches. The following throws an error " Mysql::Error: Unknown column 'users.id' in 'field list': .

Post.find_in_batches(:batch_size => 100, :select => "users.id, users.name, categories.name, posts.id", :include => [:user, :category]) do |group|
#stuff with group
end
like image 888
badnaam Avatar asked Sep 08 '10 01:09

badnaam


1 Answers

So, if you're considering using find_in_batches it probably means you have a lot of records to go through and you very well might only want select fields to be returned to you from the DB.

In Rails 3/4 you can chain find_in_batches with any other type ActiveRecord::Relation method (or at least, most... I have not tested all of them personally).

This is probably what you're looking for

User.select(:id).find_in_batches(:batch_size => 100) do |group|
   # do something with group... 
   # like print all the ids
   puts group.map(&:id)

end

If you try this in the console it generates SQL like this...

 SELECT id FROM `users` WHERE (`users`.`id` > 895846) ORDER BY `users`.`id` ASC LIMIT 100

See more info here: http://api.rubyonrails.org/classes/ActiveRecord/Batches.html

like image 106
breakpointer Avatar answered Nov 18 '22 14:11

breakpointer