在 rails 3 中批量插入 [英] Batch insertion in rails 3

查看:43
本文介绍了在 rails 3 中批量插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的 Rails 应用程序中批量插入几千条记录到数据库(在我的例子中是 POSTGRES).

I want to do a batch insert of few thousand records into the database (POSTGRES in my case) from within my Rails App.

这样做的Rails 方式"是什么?快速且正确的方法.

What would be the "Rails way" of doing it? Something which is fast and also correct way of doing it.

我知道我可以通过属性的字符串连接来创建 SQL 查询,但我想要一个更好的方法.

I know I can create the SQL query by string concatenation of the attributes but I want a better approach.

推荐答案

ActiveRecord .create 方法支持批量创建.如果数据库不支持该功能,则该方法模拟该功能,如果支持该功能,则使用底层数据库引擎.

ActiveRecord .create method supports bulk creation. The method emulates the feature if the DB doesn't support it and uses the underlying DB engine if the feature is supported.

只需传递一组选项即可.

Just pass an array of options.

# Create an Array of new objects
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])

支持块,这是共享属性的常用方式.

Block is supported and it's the common way for shared attributes.

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
  u.is_admin = false
end

这篇关于在 rails 3 中批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆