Rails Upsert (ON CONFLICT) in ActiveRecord
Use upsert with unique_by. It sends one INSERT ... ON CONFLICT DO UPDATE statement. The conflict target must match a unique index, and the example relies on a unique index on users.email.
Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.
The conversion
SQL
INSERT INTO users (email, name) VALUES ('ann@x.io', 'Ann B')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
ActiveRecord
User.upsert({ email: "ann@x.io", name: "Ann B" }, unique_by: :email)
SQL that Rails 8.1.1 generates
INSERT INTO "users" ("email","name","created_at","updated_at") VALUES ('ann@x.io', 'Ann B', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) ON CONFLICT ("email") DO UPDATE SET updated_at=(CASE WHEN ("users"."name" IS NOT DISTINCT FROM excluded."name") THEN "users".updated_at ELSE CURRENT_TIMESTAMP END),"name"=excluded."name" RETURNING "id"
What goes wrong
upsert skips validations and callbacks
It writes straight to the database, like insert_all. Rules in your model do not run. Check the data first or use a constraint.
Rails fills in timestamps
On Rails 7 and later, the statement sets created_at and updated_at, and it only changes updated_at when a value actually changed. Raw SQL would not do either.
unique_by must match a unique index
Without a matching index PostgreSQL raises an error. MySQL ignores unique_by and applies its own duplicate-key rules.
find_or_create_by is a different thing
It runs a SELECT and then an INSERT, so two processes can race and one raises or duplicates. upsert is one atomic statement.
Convert your own UPSERT (ON CONFLICT) query
Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.
Questions
How do I do ON CONFLICT DO UPDATE in Rails?
Call User.upsert({ email: "ann@x.io", name: "Ann B" }, unique_by: :email). It needs a unique index on email.
Does upsert run validations or callbacks?
No. It bypasses both, so validate the data before the call.
What is the difference between upsert and find_or_create_by?
upsert is a single atomic statement. find_or_create_by runs a SELECT and an INSERT and can race under concurrent requests.
Related conversions
Rails WHERE IN Clause in ActiveRecord
Convert SQL IN and NOT IN to Rails ActiveRecord with where(id: [..]) and where.not. Tested on Rails 8.1, including empty arrays and NULL values.
ActiveRecord Subquery in Rails
Convert a SQL IN (SELECT ...) subquery to Rails ActiveRecord with where(id: relation.select). Tested on Rails 8.1, with the NOT IN NULL trap explained.
Rails LEFT JOIN with ActiveRecord left_joins
Convert a SQL LEFT JOIN to Rails ActiveRecord with left_joins and where.missing. Tested on Rails 8.1 and PostgreSQL 16, with the generated SQL shown.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.