Bulk Insert records into Active Record table

后端 未结 5 1513
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 04:51

I found that my Model.create! statements were taking a very long time to run when I added a large number of records at once. Looked at ActiveRecord-Import but

5条回答
  •  渐次进展
    2020-11-29 05:32

    Use the activerecord-import gem. Let us say you are reading a CSV file and generating a Product catalogue and you want to insert records in batches of 1000:

    batch,batch_size = [], 1_000 
    CSV.foreach("/data/new_products.csv", :headers => true) do |row|
      batch << Product.new(row)
    
      if batch.size >= batch_size
        Product.import batch
        batch = []
      end
    end
    Product.import batch
    

提交回复
热议问题