Magical Bulk Insertion in Rails 6

Moiz Ali
2 min readMay 10, 2022

Introduction

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

On the first take, you would come up with this version

Problematic Region

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

Workaround in Oldies

If you’re running on Rails 5 and older versions, you might face the situation where writing raw customized SQL or using gems like activerecord-import is the final option you are 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*

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.
Happy Coding!

--

--

Moiz Ali

I am a Software Engineer who loves to transform ideas into reality, devise solutions, write code and articles.