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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With