skip to content

In Active Record, how do insert_all, insert_all! and upsert_all differ for importing a nightly grocery price feed, and what do they skip compared with create?

level: middleimportance: must knowfreq 52%

answer

  1. one INSERT, many rows
  2. skip, raise or update on conflict
  3. no models, validations or callbacks
  4. values still type-cast
  5. every hash needs the same keys

basics

~20 s

All three write an array of hashes in one INSERT without instantiating models or running validations and callbacks. insert_all skips rows that hit a unique index, insert_all! raises ActiveRecord::RecordNotUnique and inserts nothing, and upsert_all updates the existing row instead.

solid answer

~40 s

`Price.insert_all(rows)` builds one `INSERT` for the whole array and adds a skip-on-conflict clause, so duplicates by any unique index are dropped silently. `insert_all!` sends a plain `INSERT`; one duplicate raises `ActiveRecord::RecordNotUnique` and, the statement being atomic, no row is written. `upsert_all` turns conflicts into updates of the existing row. None of them instantiates a model or runs validations or callbacks, unlike `create`, but values are still type-cast and serialized through the attribute types, and `created_at` / `updated_at` are filled by default. Every hash must have the same keys, or Rails raises `ArgumentError`. They return an `ActiveRecord::Result`, holding the inserted primary keys on adapters that support `RETURNING`. For a large feed, slice it, `rows.each_slice(1_000)`, so each statement stays a reasonable size.

code

ruby · 8 lines
ruby
rows = feed.map do |line|
  { product_id: line.product_id, recorded_on: line.date, amount_cents: line.cents, currency: line.currency || "EUR" }
end

rows.each_slice(1_000) do |slice|
  result = Price.insert_all(slice, unique_by: %i[product_id recorded_on])
  Rails.logger.info("prices inserted: #{result.rows.size}")
end

go deeper

for a junior

Know that insert_all writes many rows in one statement and skips validations and callbacks, and how insert_all, insert_all! and upsert_all differ on duplicates.

for a middle

Explain what is still applied (type casting, timestamps, scope attributes), the same-keys rule and the Result return value.

for a senior

Move skipped validations into database constraints, slice large feeds, and replace callback side effects with an explicit post-import step.

for a principal

Decide where import correctness lives, in constraints, a staging table or application checks, and how a failed nightly import is detected and replayed.

## Why bulk inserts exist Importing a nightly price feed of 80,000 rows with `Price.create!(attrs)` means 80,000 models, 80,000 validation runs, 80,000 callback chains and 80,000 `INSERT` statements, each in its own transaction. Active Record's bulk methods trade all of that for **one statement per call**: they take an `Array` of `Hash`es and write them with a single multi-row `INSERT`. ## The three variants | Method | On a unique-index conflict | SQL it adds (PostgreSQL) | |---|---|---| | `insert_all` | skips the conflicting row | `ON CONFLICT DO NOTHING` | | `insert_all!` | raises `ActiveRecord::RecordNotUnique`; no rows written | none, a plain `INSERT` | | `upsert_all` | updates the existing row | `ON CONFLICT (...) DO UPDATE SET ...` | Single-row versions exist as well: `insert`, `insert!` and `upsert`, each a thin wrapper over the `_all` form with one hash. - `insert_all` treats a row as a duplicate when it conflicts with **any** unique index on the table, unless `unique_by:` narrows it to one (PostgreSQL and SQLite). On MySQL the skip is written as a no-op `ON DUPLICATE KEY UPDATE`. - `insert_all!` is the strict import: a duplicate means the feed is wrong, and the whole statement fails. - `upsert_all` by default updates every column it was given except the primary key, read-only attributes and the `unique_by:` columns. ## What they skip, and what they keep Compared with `create`, the bulk methods **skip**: 1. **Model instantiation**: no `Price` objects are built; the return value is an `ActiveRecord::Result`. 2. **Validations**: `validates :amount_cents, numericality: true` does not run, so bad data reaches the database unless a constraint stops it. 3. **Callbacks**: no `before_save`, no `after_create_commit`, so nothing that hangs off them (cache busting, search indexing, broadcasts) happens. They still **keep**: - **Type casting and serialization**: each value goes through the attribute's type, so an `enum` symbol becomes its stored value, a serialized column is encoded and a string `"1.99"` is cast for a decimal column. - **Timestamps**: with the model's `record_timestamps` (true by default), `created_at` and `updated_at` are set from the database's current time; pass `record_timestamps: false` to turn that off. - **Scope attributes**: `store.prices.insert_all(rows)` fills `store_id` from the association, and `create_with(source: "feed")` adds defaults to every row. ## Rules that trip people up - **Same keys in every hash.** A feed row missing `currency` raises `ArgumentError` ("All objects being inserted must have the same keys"); normalise rows first, filling `nil` where a value is absent. - **Unknown columns** raise `ActiveModel::UnknownAttributeError` before any SQL runs. - **Empty input** returns an empty `Result` without touching the database. - **Statement size**: the values are written into the SQL text, so a 500,000-row call becomes one enormous statement. Slice the input: ```ruby feed_rows.each_slice(1_000) do |slice| Price.insert_all(slice, unique_by: %i[product_id recorded_on]) end ``` ## Bulk methods versus a loop of create! | Concern | `create!` in a loop | `insert_all` and friends | |---|---|---| | Statements | one `INSERT` per row | one per call | | Validations | run | skipped | | Callbacks | run | skipped | | Returns | model instances | `ActiveRecord::Result` | | Duplicate handling | `RecordInvalid` or `RecordNotUnique` per row | skip, raise or update per method | ## Choosing for the price feed 1. Prices are history, one row per product per day, and a re-sent feed should be harmless: `insert_all` with `unique_by: %i[product_id recorded_on]` skips what is already there. 2. The feed must be exactly right, and a duplicate is a supplier error worth stopping for: `insert_all!` inside a transaction with the rest of the import. 3. The table holds the **current** price per product, and the feed replaces it: `upsert_all` keyed by the product's unique column. ## After the import Because no model is saved, nothing attached to saving happens: - `belongs_to ... counter_cache: true` counters are not incremented; - `after_commit` work such as cache expiry, search indexing or Turbo broadcasts does not run; - `touch: true` on an association does not bump the parent. Plan those as explicit steps: recount once after the import, enqueue one job per slice with the returned ids, or expire a cache key for the whole price list. Whichever you pick, the skipped validations move into **database constraints** (`NOT NULL`, `CHECK (amount_cents >= 0)`, unique indexes), and anything callbacks used to do moves into an explicit step after the import, such as one cache clear or one job per slice.

  • On PostgreSQL, how do you tell how many feed rows insert_all actually inserted?
    The returned `ActiveRecord::Result` holds one row per inserted record, the primary key by default through `RETURNING`, and skipped duplicates are not in it. `result.rows.size` is the inserted count. On MySQL, which has no `RETURNING`, you count before and after or compare against the unique keys.
  • Why might insert_all succeed while Price.create! would have failed for the same row?
    `create!` runs the model's validations, while `insert_all` sends the row straight to the database. A rule enforced only by `validates`, such as a positive amount, is not checked, so the row is stored unless a database constraint rejects it.

  • insert_all runs each model's validations before building the INSERT.
  • insert_all! inserts the valid rows and raises only for the duplicate.
  • Bulk inserts leave created_at and updated_at NULL.
  • insert_all returns the new Price records with their ids.
  • Rows may have different keys; missing columns are filled with NULL.