Skip to content

Model.insert_all can accept an array of records with separate column names

Created by: robertomiranda

Motivation / Background

Expanding the Model.insert_all functionality to receive an array containing records and column names separately. This improvement eliminates the need for records to be in the hash format, providing a more streamlined approach, especially useful for handling large datasets when both the order of attributes and their alignment with the table structure are known in advance.

column_names = [:name, :author_id]
book_batches.each do |book_batch|
	Book.insert_all(book_batch, column_names: column_names)
end

This update enables users to provide an array of arrays for the records, while also specifying the column names separately. This enhancement enhances code flexibility and readability, simplifying data insertion without requiring pre-formatting into hashes.

Detail

  • Modified insert_all method to accept an array of arrays for records.
  • Added support for specifying column names separately using the columns option.
Book.insert_all([
  ["Rework", 1],
  ["Patterns of Enterprise Application Architecture", 1]
], column_names: [:name, :author_id])

To showcase the API proposal, I opted for the simplest approach, which involved converting the array of records and column names into a Hash, as it aligns with the existing code.

Merge request reports