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

查看:119
本文介绍了在轨道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的<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-create"><$c$c>.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.

只是通过一组选项。

# 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

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

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