TIL: ActiveRecord-import gem for bulk saves!

Do you suffer from a one to many relationship where many is huge? Do you have to create these often and suffer from N+1's or nasty non-obfuscated SQL? Or did you solve it at one point and time by mastering Arel, but now have forgotten the level of wizardry you once achieved?

Dread no more my friends! I present a simple solution in the form of yet-another-gem!

activerecord-import Provides a simple interface to build & submit a single create statements for all of your associated objects at one time. Here's an example directly from their docs:

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

This generates a simple insert statement to persist those 10 books instead of calling save (and inserting) 10 times in the loop.

Another example shows a much more intensive use case. Assume that Books has_many Reviews:

books = []  
10.times do |i|  
  book = Book.new(:name => "book #{i}")
  book.reviews.build(:title => "Excellent")
  books << book
end  
Book.import books, recursive: true  

Passing recursive: true into import tells activerecord-import to deep persist, while still only creating two insert statements.

Ah, the wonders that 'yet-another-gem' can bring to your app. Enjoy!