Efficient bulk update in ActiveRecord?

How to effectively massage updates in ActiveRecord? I am trying to populate a column that depends on another column.

Now this is my code:

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 does not increase efficiency. transaction seems to be the wrong way to do this. Any ideas?

+4
source share
1 answer

In general, instead of distributing bulk updates over n sql record statements, you can combine them all into one using update_all , (Depending on many variables) this can improve overall performance.

+7
source

Source: https://habr.com/ru/post/1444956/


All Articles