Bulk Insert records into Active Record table

后端 未结 5 1532
隐瞒了意图╮
隐瞒了意图╮ 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:27

    Using a transaction speeds up bulk inserts a lot!

    Model.transaction do
        many.times{ Model.create! }
    end
    

    If multiple Models are involved, do a Model.transaction for each model, which is affected:

    Model1.transaction do
        Model2.transaction do
            many.times do
                m1 = Model1.create!
                m1.add_model2
            end
        end
    end
    

提交回复
热议问题