Batch Insertion in Rails 3

Batch insertion in rails 3

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

How to implement bulk insert in Rails 3

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.

Bulk Insert records into Active Record table

I started running into problems with large numbers of records (> 10000), so I modified the code to work in groups of 1000 records at a time. Here is a link to the new code:

https://gist.github.com/jackrg/76ade1724bd816292e4e

Batch insert documents on mongoid relations

Try this:

user.messages.create(batch)

Also in your case you need to add this to the Message model:

field :name

=== UPDATE ===
Perhaps this could be useful:

user = ... # get user somehow
batch = [{name: "dsfdf" },{name: "dfsdfh"}].collect { |msg| {name: msg.fetch(:name), user_id: user.id} }
Message.collection.insert(batch)

How do I retrieve a list of created IDs for bulk insert in Active Record?

If you are using mysql and you are not inserting more rows in another script/process, you can get the id of the first row inserted by using last_insert_id()

    first_id = ActiveRecord::Base.connection.execute("select last_insert_id()").first[0]

And then the ids of the other records are sequentially generated.

i.e.

    data = %w(one two three)
to_insert = "('" + data.join("'), ('") + "')"
Model.connection.insert("INSERT INTO models(name) VALUES #{to_insert}")
first_id = ActiveRecord::Base.connection.execute("select last_insert_id()").first[0].to_i
hash = {}
data.each_with_index {|d, i| hash[first_id + i] = d}


Related Topics



Leave a reply



Submit