Group operations in a transaction

ActiveRecord wraps the creation or update of a record in a single transaction. Multiple inserts will then generate many transactions (one for each insert). Grouping multiple inserts in one single transaction will speed things up.

Insead of:

 my_collection.each do |q|
   Report.create({:phrase => q})
 end

Use:

Report.transaction do
 my_collection.each do |q|
   Report.create({:phrase => q})
 end
end

or for rolling back the whole transaction if any insert fails, use:

Report.transaction do
 my_collection.each do |q|
   report = Report.new({:phrase => q})
   report.save!
 end
end

Permanent link to this article: https://blog.openshell.in/2010/11/group-operations-in-a-transaction/

Leave a Reply

Your email address will not be published.