[英]In rails how to Insert thousands of records in table
I have created API using Ruby on Rails. 我已经使用Ruby on Rails创建了API。 when I call an API endpoint to insert more than 1000 records it gets crashed.
当我调用API端点以插入1000多个记录时,它崩溃了。 currently, I am using database
Mysql2
当前,我正在使用数据库
Mysql2
my code is 我的代码是
quantity.times do
User.create(first_name: "John")
end
where quantity
is a number of records need to insert and it can be any number like 10000, 4000000. 其中,
quantity
是需要插入的记录数,可以是10000、4000000等任意数字。
can anyone suggest me how can I do this very efficiently without breaking my server 谁能建议我如何在不中断服务器的情况下非常有效地做到这一点
ActiveRecord.import ActiveRecord.import
items = []
quantity.times.each do |row|
items << User.new(name: "john")
end
User.import(items)
Just have a look at these benchmarks to get a sense of just how much faster this option is. 只需查看这些基准 ,即可了解该选项有多快。 Instead of separate transactions, commits, and inserts that a
Model.create
generates SQL for, this handles it in a single query. 代替单独的事务,提交和插入由
Model.create
生成SQL的事务,这将在单个查询中处理它。
References 参考文献
try this gem 'activerecord-insert_many' . 试试这个gem'activerecord-insert_many' 。 In the source code, find tests and you can see how to consume the gem.
在源代码中,找到测试,您可以看到如何使用gem。
Thanks, Ajith 谢谢,Ajith
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.