Skip to content

double decrement counter_cache when updating association nil #31491

@hw676018683

Description

@hw676018683

Steps to reproduce

class A < ApplicationRecord
  has_many :bs
end


class B < ApplicationRecord
  belongs_to :a, counter_cache: true
end
  a = A.create
  b = a.bs.create
a.reload.bs_count # => 1
b.update a: nil
a.reload.bs_count # => -1

update sql

   (0.2ms)  BEGIN
  A Update All (0.4ms)  UPDATE "as" SET "bs_count" = COALESCE("bs_count", 0) - 1 WHERE "as"."id" = $1  [["id", 1]]
  B Update (0.3ms)  UPDATE "bs" SET "a_id" = $1, "updated_at" = $2 WHERE "bs"."id" = $3  [["a_id", nil], ["updated_at", "2017-12-17 06:02:26.884865"], ["id", 28]]
  A Update All (0.2ms)  UPDATE "as" SET "bs_count" = COALESCE("bs_count", 0) - 1 WHERE "as"."id" = $1  [["id", 1]]
   (0.2ms)  COMMIT

Expected behavior

a.reload.bs_count # => 1
b.update a: nil
a.reload.bs_count # => 0

Actual behavior

as the above

System configuration

Rails version: 2.3.1

Ruby version: 5.2.0.beta2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions