Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently bulk-updating in ActiveRecord?

How do I efficiently bulk-update records in ActiveRecord? I'm trying to populate a column which depends on another column.

This is my code now:

Tweet.find_in_batches do |group|
  to_be_saved = []
  group.each do |t|
    t.creation_date_posix = DateTime.strptime(t.creation_date_str, '%m/%d/%Y %H:%M').to_time.to_i
    to_be_saved << t
  end
  Tweet.transaction do
    to_be_saved.each{|t| t.save}
  end
end

but it doesn't improve efficiency. Apparently transaction is not the right way to do it. Any ideas?

like image 588
luca Avatar asked Nov 08 '12 22:11

luca


1 Answers

In general, rather than spreading out bulk updates over n sql write statements, you can combine them all into one using update_all. (Depending on a lot of variables) this can improve your overall performance.

like image 75
pje Avatar answered Nov 10 '22 06:11

pje