Christian-G
Christian-G

Reputation: 2361

Insert multiple records at once

I have a group of radio buttons returning the following hash:

{"1"=>"1", "3"=>"2"}

The key represents the event_id and the value represents the regoption_id. I need to insert these to the subscriptions table preferably all at once. I tried the following:

params[:children].each do |child|    
  Subscription.create({:event_id => child[0], :regoption_id => child[1]}).save
end

This ends up saving just one radio group, not all in the hash. Any ideas on how to do this?

Upvotes: 0

Views: 118

Answers (1)

Jim Stewart
Jim Stewart

Reputation: 17323

There's a gem called activerecord-import that will insert multiple records efficiently. It works with many popular DB backends, and will just do the right thing with most of them. This does exactly what you want: it accepts an array of object instances, or an array-of-hashes-of-values, and inserts them into a table in a single statement.

Here's a usage example right from the gem documentation:

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

Upvotes: 1

Related Questions