Skip to content

Sometimes create_association does not delete existing records #47554

@willnet

Description

@willnet

Steps to reproduce

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  # Activate the gem you are reporting the issue against.
  gem "activerecord", "~> 7.0.0"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
  end

  create_table :addresses, force: true do |t|
    t.references :user
  end
end

class User < ActiveRecord::Base
  has_one :address, -> { order(id: :desc) }, dependent: :destroy
end

class Address < ActiveRecord::Base
  belongs_to :user
end

class BugTest < Minitest::Test
  def test_association_stuff
    user = User.create!
    Address.create(user: user)
    assert_equal 1, Address.count
    user.create_address!
    assert_equal 1, Address.count # fail
  end
end

-> { order(id: :desc) } in the reproduction code is written to reproduce 100%. Some environments may reproduce it without this argument.

The create_association method may load a record for deletion after INSERT, and if a newly created record is loaded at that time, the DELETE statement will not be issued and multiple records will exist.

Expected behavior

user.create_address! remove old address record.

Actual behavior

user.create_address! doesn't remove old address record.

System configuration

Rails version: 7.0.4.2
Ruby version: 3.2.1

This PR already fixed the bug. So this problem does not occur on the main branch.

It would be great if someone could backport #46386 to the 7-0-stable branch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions