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)开发者_StackOverflow
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.
I suggest using the activerecord-import gem until the mainline activerecord has support for bulk inserts.
It's fairly simple to use, for instance bulk inserting a bunch of "Rating" records:
# Example database record/model
class Rating < ActiveRecord::Base
end
ratings = []
# Create some fake data here..
100.times do |i|
ratings << Rating.new({ stars: (rand * 5).to_i }) # random star rating
end
# Bulk import ratings (single query)
Rating.import(ratings)
精彩评论