In Rails 8.1, how do upsert_all's unique_by:, update_only:, on_duplicate: and returning: shape a nightly grocery price sync keyed by sku?
answer
- conflict target from a unique index
- PostgreSQL and SQLite only
- update_only versus raw SQL
- updated_at moves only on change
- returning: needs Arel.sql for strings
basics
~20 sunique_by: names the unique index that decides a conflict (PostgreSQL and SQLite only), update_only: limits which columns are overwritten, on_duplicate: takes custom Arel.sql update SQL, and returning: chooses the columns sent back in the ActiveRecord::Result.
solid answer
~50 s`Product.upsert_all(rows, unique_by: :sku)` makes the index on `sku` the conflict target; it must match a unique index by columns or by index name, or Rails raises `ArgumentError` ("No unique index found"), and on MySQL, which has no conflict target, passing it raises too. By default every given column except the primary key, read-only attributes and the `unique_by` columns is overwritten; `update_only: [:price_cents]` narrows that, while `on_duplicate: Arel.sql("price_cents = LEAST(products.price_cents, EXCLUDED.price_cents)")` supplies your own SET clause (not both at once). With timestamps on, `created_at` is kept and `updated_at` moves only when an updated column actually changed. `returning: %w[id sku]` sends those columns back on PostgreSQL, SQLite and MariaDB; a raw string must be wrapped in `Arel.sql`. In Rails 8.1, a `nil` id in a row becomes the column's default, so new and existing rows can share one upsert.
code
ruby · 9 linesfeed_rows.uniq { |row| row[:sku] }.each_slice(1_000) do |slice|
result = Product.upsert_all(
slice,
unique_by: :sku,
update_only: [:price_cents],
returning: %w[id sku]
)
PriceChangeNotifier.enqueue_for(result.rows.map(&:first))
endgo deeper
Know that upsert_all inserts new rows and updates existing ones in one statement, and that unique_by: says which unique column decides a match.
Explain the default updated columns, update_only: versus on_duplicate:, and how created_at and updated_at behave on conflict.
Handle adapter limits (no unique_by: or returning: on MySQL), use returning: to drive follow-up work, and lean on 8.1's nil-id default for mixed new and existing rows.
Decide whether a feed sync belongs in upsert_all, a staging table plus set-based SQL, or per-record code, given what callbacks and audits the business requires.
## The sync being built A grocery app keeps one row per product with its **current** price. Each night a supplier feed arrives keyed by `sku`: some skus are new, most exist and some prices changed. `upsert_all` does it in one statement per slice, and four options decide how. ```ruby Product.upsert_all( feed_rows, # [{ sku: "A1", name: "Oat milk 1L", price_cents: 189 }, ...] unique_by: :sku, update_only: [:price_cents], returning: %w[id sku] ) ``` ## unique_by: which index decides a conflict - By default the conflict target is the **primary key**. A feed that does not know your ids needs `unique_by:`. - It accepts columns (`:sku`, `%i[store_id sku]`) or an index name (`:index_products_on_sku`). Rails looks the index up in the schema cache and raises `ArgumentError` ("No unique index found for sku") when no unique index matches. Pairing it with a dumped schema cache avoids a lookup at run time. - A **partial** unique index works: its `WHERE` clause is copied into the conflict target. - It is **PostgreSQL and SQLite only**. MySQL's `ON DUPLICATE KEY UPDATE` reacts to any unique key, so passing `unique_by:` there raises `ArgumentError` ("does not support :unique_by"). ## Which columns get overwritten There are three modes, and the last two cannot be combined (`ArgumentError`): | Mode | What a conflicting row gets | |---|---| | default | every column in the hashes except the primary key, read-only attributes and the `unique_by` columns | | `update_only: [:price_cents]` | only the listed columns | | `on_duplicate: Arel.sql("...")` | exactly the SQL you write, and you must list every column yourself | `on_duplicate:` is the escape hatch for rules that need the old and new values together, such as keeping the lower price: `Arel.sql("price_cents = LEAST(products.price_cents, EXCLUDED.price_cents)")` on PostgreSQL. A plain string there raises `ArgumentError`, because Rails only accepts raw SQL it can see you marked as trusted. ## Timestamps on an upsert With the model's `record_timestamps` on (the default): - **New rows** get `created_at` and `updated_at` from the database's current time. - **Existing rows** keep their `created_at`: unless your hashes include it, it is not among the columns written on conflict. - `updated_at` on an existing row is bumped **only if** at least one updated column differs from the stored value; Rails generates a `CASE` comparing each column with the incoming one. A nightly feed that changes nothing leaves `updated_at` alone, which keeps "recently changed" queries and caches keyed on it honest. - `record_timestamps: false` disables both, and with `on_duplicate:` the automatic `updated_at` is not added, so set it in your own SQL if you need it. ## returning: what comes back - `upsert_all` returns an `ActiveRecord::Result`. On adapters that support `RETURNING` (PostgreSQL, SQLite 3.35+, MariaDB 10.5+) it holds the primary key of every inserted or updated row by default. - `returning: %w[id sku]` picks columns; `returning: false` drops the clause. - An SQL expression must be wrapped: `returning: Arel.sql("id, sku AS product_sku")`. A plain string raises `ArgumentError` ("Dangerous query method"). - On MySQL (as opposed to MariaDB 10.5+), passing `returning:` raises `ArgumentError`, because the adapter does not support it. ## What changed in Rails 8.1 1. **`nil` primary keys get the default.** A row with `id: nil` is written with the adapter's default insert value, so on PostgreSQL brand-new products (no id) and known ones (with id) can share one `upsert_all` keyed by the primary key instead of failing on a NULL id. 2. **Relations are reset** after `insert_all`/`upsert_all`, matching `update_all`. 3. **Deprecated**: calling them on an association that holds unpersisted records, such as products built with `store.products.build` and not saved, because those records are lost after the operation. ## Pitfalls worth naming - Every hash still needs the **same keys**; a feed line without `name` breaks the slice. - Two rows with the same `sku` in one statement are a feed problem to remove before the call; deduplicate with `feed_rows.uniq { |r| r[:sku] }`. - No validations or callbacks run, so a `CHECK (price_cents >= 0)` constraint is the only guard against a negative price.
- Why can't update_only: and on_duplicate: be combined on upsert_all?Both define the SET clause for conflicting rows: `update_only:` generates one from a column list, `on_duplicate:` is one you wrote. Rails raises `ArgumentError` rather than guess how to merge them; put every column you need in the custom SQL instead.
- What does upsert_all do when every column in the rows is either the primary key or a unique_by column?There is nothing left to update, so Rails turns the upsert into a skip: conflicting rows are left as they are, the same as `insert_all`, and only new keys are inserted.
- unique_by: works the same on MySQL as on PostgreSQL.
- upsert_all overwrites created_at on every existing row.
- updated_at is bumped on every conflicting row, changed or not.
- returning: accepts any SQL string without Arel.sql.
- update_only: and on_duplicate: can be combined for finer control.
- unique_by: can name any column, indexed or not.
Assumes Rails 8.1, where nil primary keys in insert_all/upsert_all rows become the adapter's default value and bulk calls reset the relation they run on.