method

insert_all

Importance_3
Ruby on Rails latest stable (v7.1.3.2) - 0 notes - Class: ClassMethods
insert_all(attributes, returning: nil, unique_by: nil, record_timestamps: nil) public

Inserts multiple records into the database in a single SQL INSERT statement. It does not instantiate any models nor does it trigger Active Record callbacks or validations. Though passed values go through Active Record’s type casting and serialization.

The attributes parameter is an Array of Hashes. Every Hash determines the attributes for a single row and must have the same keys.

Rows are considered to be unique by every unique index on the table. Any duplicate rows are skipped. Override with :unique_by (see below).

Returns an ActiveRecord::Result with its contents based on :returning (see below).

Options

:returning

(PostgreSQL and SQLite3 only) An array of attributes to return for all successfully inserted records, which by default is the primary key. Pass returning: %w[ id name ] for both id and name or returning: false to omit the underlying RETURNING SQL clause entirely.

You can also pass an SQL string if you need more control on the return values (for example, returning: Arel.sql("id, name as new_name")).

:unique_by

(PostgreSQL and SQLite only) By default rows are considered to be unique by every unique index on the table. Any duplicate rows are skipped.

To skip rows according to just one unique index pass :unique_by.

Consider a Book model where no duplicate ISBNs make sense, but if any row has an existing id, or is not unique by another unique index, ActiveRecord::RecordNotUnique is raised.

Unique indexes can be identified by columns or name:

unique_by: :isbn
unique_by: %i[ author_id name ]
unique_by: :index_books_on_isbn
:record_timestamps

By default, automatic setting of timestamp columns is controlled by the model’s record_timestamps config, matching typical behavior.

To override this and force automatic setting of timestamp columns one way or the other, pass :record_timestamps:

record_timestamps: true  # Always set timestamps automatically
record_timestamps: false # Never set timestamps automatically

Because it relies on the index information from the database :unique_by is recommended to be paired with Active Record’s schema_cache.

Example

# Insert records and skip inserting any duplicates.
# Here "Eloquent Ruby" is skipped because its id is not unique.

Book.insert_all([
  { id: 1, title: "Rework", author: "David" },
  { id: 1, title: "Eloquent Ruby", author: "Russ" }
])

# insert_all works on chained scopes, and you can use create_with
# to set default attributes for all inserted records.

author.books.create_with(created_at: Time.now).insert_all([
  { id: 1, title: "Rework" },
  { id: 2, title: "Eloquent Ruby" }
])
Show source
Register or log in to add new notes.