如何在 Rails 3 中实现批量插入 [英] How to implement bulk insert in Rails 3

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

问题描述

我需要将一系列电子邮件作为不同的记录插入到我的联系人表中.这怎么可能.

I need to insert a array of emails as different records into my contacts table. How can this be done.

Eg: @email = ["a@b.com", "c@d.com", "e@f.com", ... ]

我不想使用.

  @email.each do |email|
     @contact = Contact.new
     @contact.email = email
     @contact.save
  end

这会导致 n 个插入请求.我只需要一个插入查询来插入这些值.这如何在 rails 3.0.9(最好是 MySQL)中完成.请帮忙

This cause n insert quires. I just need a single insert query to insert these values. How can this be done in rails 3.0.9 (and ideally MySQL). Please help

推荐答案

activerecord-import 实现 AR#import

activerecord-import implements AR#import

activerecord-import 是一个使用 ActiveRecord 批量插入数据的库.

activerecord-import is a library for bulk inserting data using ActiveRecord.

看看它是如何工作的:

books = []
10.times do |i| 
  books << Book.new(:name => "book #{i}")
end
Book.import books

项目的主页位于 Githubwiki.

Project's home is on Github and it's wiki.

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

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