问题
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