upsert_all
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (38)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
upsert_all(attributes, returning: nil, unique_by: nil)
public
Updates or inserts (upserts) 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.
Returns an ActiveRecord::Result with its contents based on :returning (see below).
Options
- :returning
-
(PostgreSQL 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.
- :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
Because it relies on the index information from the database :unique_by is recommended to be paired with Active Record’s schema_cache.
Examples
# Inserts multiple records, performing an upsert when records have duplicate ISBNs. # Here "Eloquent Ruby" overwrites "Rework" because its ISBN is duplicate. Book.upsert_all([ { title: "Rework", author: "David", isbn: "1" }, { title: "Eloquent Ruby", author: "Russ", isbn: "1" } ], unique_by: :isbn) Book.find_by(isbn: "1").title # => "Eloquent Ruby"