Rails save massive hash data to database

戏子无情 提交于 2019-12-13 03:27:43

问题


I have a Hash with 2M data. I need to transfer all data from hash to database. Hash keys fit with database columns.

I'm not sure the way I use below is the best way.

# users is a hash with 2M data.
users.each do |u|
   user = User.new(u)
   user.save!
end

what is the best way to iterate through this kind of massive data with Rails?


回答1:


ActiveRecord.create accepts hashes too. Therefore I would just try:

User.create(users)

2M might be a bit too big and you might need to work in batches. But I suggest this to be faster than one insert per record.




回答2:


Try using active record import gem(https://github.com/zdennis/activerecord-import#hashes). You can even insert records with batching(https://github.com/zdennis/activerecord-import#batching)

User.import(users, batch_size: 1000)


来源:https://stackoverflow.com/questions/57596533/rails-save-massive-hash-data-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!