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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With