Magical Bulk Insertion in Rails 6
Moiz Ali

Moiz Ali @moiz1524

About: I am working as a Software Engineer in SystemPlus. Interests in cloud-based web applications in Ruby on Rails, JavaScript and Node.js

Location:
Lahore, Pakistan
Joined:
Dec 21, 2020

Magical Bulk Insertion in Rails 6

Publish Date: May 10 '22
4 3

Introduction

In modern apps we mostly have a requirement which allows user to perform bulk actions. Like insertion of records is the one.

On the first take you would come up with this version

Image description

Problematic Region

So what the hack? Above code is a classic situation of multiple sql insert calls, each for a movie creation. This yields slow performance, eventually bad code!

Workaround in Oldies

If you're running on Rails 5 and older versions, you might face the situtation where writing raw customized SQL or using gems like activerecord-import is the final option you left with.

Magic of Rails 6

But once you're up and running here, there is a method for you, built out of the box namely insert_all

Pick your wand and lets get started!

*We are discussing a Car model here

Image description

Documentation here: https://apidock.com/rails/v6.0.0/ActiveRecord/Persistence/ClassMethods/insert_all

Do you find it useful? Let me know inside comments!
Follow me for more interesting snacks.

Comments 3 total

  • Moiz Ali
    Moiz AliMay 11, 2022

    Follow for more amazing content :)

  • Can Olcer
    Can OlcerMay 12, 2022

    This is great for simple use cases. For more involved cases, e.g. if you have associations or do want some kind of validation, the Activerecord-Import gem is awesome.

Add comment