Sunday, November 28, 2010

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

0 comments:

Post a Comment