instance method insert_all!

Ruby on Rails 8.1.2

Since v7.2.3

Available in: v7.2.3 v8.0.4 v8.1.2

Signature

insert_all!(attributes, returning: nil, record_timestamps: nil)

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.

Raises ActiveRecord::RecordNotUnique if any rows violate a unique index on the table. In that case, no rows are inserted.

To skip duplicate rows, see #insert_all. To replace them, see #upsert_all.

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

Options
:returning

(PostgreSQL, SQLite3, and MariaDB 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")).

: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
Examples
# Insert multiple records
Book.insert_all!([
  { title: "Rework", author: "David" },
  { title: "Eloquent Ruby", author: "Russ" }
])

# Raises ActiveRecord::RecordNotUnique because "Eloquent Ruby"
# does not have a unique id.
Book.insert_all!([
  { id: 1, title: "Rework", author: "David" },
  { id: 1, title: "Eloquent Ruby", author: "Russ" }
])

Parameters

attributes req
returning key = nil
record_timestamps key = nil
Source
# File activerecord/lib/active_record/relation.rb, line 810
    def insert_all!(attributes, returning: nil, record_timestamps: nil)
      InsertAll.execute(self, attributes, on_duplicate: :raise, returning: returning, record_timestamps: record_timestamps)
    end

Defined in activerecord/lib/active_record/relation.rb line 810 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Relation

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close