Posted almost 10 years ago. Visible to the public. Repeats.

ActiveRecord: Creating many records works faster in a transaction

When you need to insert many records into the same table, performance may become an issue.

What you can do to save time is to open a transaction and save multiple records within that transaction:

Copy
transaction do 500.times { Model.create! } end

Although you will still trigger 500 INSERT statements, they will complete considerably faster.

When I tried it out with a simple model and 500 iterations, the loop completed in 1.5 seconds vs. 6 seconds without a transaction.

Alternative

Another fast way to insert many records is to have a single INSERT statement describing multiple rows.

In Rails 6+ you can do so with ActiveRecord::Base.insert_all. This is very fast, but you won't get the usual guarantees from validations or transactions.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
12 days ago
by Henning Koch
Keywords:
activerecord
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more