Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple Rails ActiveRecord records in one call/query

In one of my Rails apps' AR classes, I ended up with an array of many newly initialised ActiveRecord objects.

I want to be able to save them to the DB in an efficient way, ideally, in one method call. At the moment, i have them wrapped inside a transaction.

Something like:

Object.transaction do
  @objects.map(&:save)
end

is there a more efficient solution to create/update an array of records?

like image 281
cnikolaou Avatar asked Jan 20 '23 12:01

cnikolaou


1 Answers

You do right with wrapping everything into a transaction, becuase then the database flushes and updates indices only once.

You cannot insert many objects in a single SQL statement in standard SQL. MySQL can do that, but this is non-default. I doubt there is a huge performance advantage to this.

If this code is really time critical, you could run it asynchronously (by either moving it into a background thread - note there are issues with ActiveRecord and multithreading - or let it be executed by a worker. Or you could generate the SQL by hand - AR is not extremely efficient in doing so. However, I would go that way only if this is extremely critical, and would consider it a hack then.

like image 126
radiospiel Avatar answered Jan 22 '23 02:01

radiospiel