#58732·rails

Building (not saving) a has_one association deletes the existing one

Author: regan-wrapbookCreated Sep 10, 2026Updated Sep 11, 2026

Steps to reproduce

class Govt < ApplicationRecord
  has_one :nuclear_codes, dependent: :destroy
end

class NuclearCodes < ApplicationRecord
  belongs_to :govt
end

govt = Govt.create
nuclear_codes = govt.build_nuclear_codes
govt.save 
# => INSERT INTO "nuclear_codes"
govt.build_nuclear_codes
# => DELETE FROM "nuclear_codes"

Another path to the same bug:

govt = Govt.create
nuclear_codes = govt.build_nuclear_codes
govt.save 
# => INSERT INTO "nuclear_codes"
Govt.new(id: govt.id)
# => DELETE FROM "nuclear_codes"

build / new imply (heavily!) a staging state, waiting for .save to commit to the db.

The idea of build destroying a record seems insane.

This has been brought up 13 years ago https://github.com/rails/rails/issues/12705 and 9 years ago https://github.com/rails/rails/issues/28821 but never acted on.

Expected behavior

DB writes (including DESTROY) should happen on save, not on new or build

Actual behavior

DESTROY is triggered when calling new or build

System configuration

Rails version: 8.0.0

Ruby version: 3.4.8