Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement bulk insert in Rails 3

Tags:

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

Eg: @email = ["[email protected]", "[email protected]", "[email protected]", ... ] 

I dont want to use.

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

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

like image 770
Amal Kumar S Avatar asked Dec 14 '11 13:12

Amal Kumar S


1 Answers

activerecord-import implements AR#import

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

see how it works:

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

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

like image 98
Anatoly Avatar answered Oct 08 '22 22:10

Anatoly