Rails 将海量哈希数据保存到数据库 [英] Rails save massive hash data to database
本文介绍了Rails 将海量哈希数据保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有 2M 数据的 Hash
.我需要将所有数据从 hash
传输到 database
.哈希键适合数据库列.
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
使用 Rails 遍历此类海量数据的最佳方法是什么?
what is the best way to iterate through this kind of massive data with Rails?
推荐答案
尝试使用活动记录导入 gem(https://github.com/zdennis/activerecord-import#hashes).您甚至可以使用批处理插入记录(https://github.com/zdennis/activerecord-import#批处理)
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)
这篇关于Rails 将海量哈希数据保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文