Skip to content

Decrement counter trigger twice when associated object removed #33117

@vavgustov

Description

@vavgustov

Steps to reproduce

Let's say we have 2 models:

class Author < ApplicationRecord
  has_many :books
end
class Book < ApplicationRecord  
  belongs_to :author, optional: true, counter_cache: true

  accepts_nested_attributes_for :author
end

Then:

Author.create(name: 'author name')
3.times { Book.create(title: 'book title', author: Author.last) }
Book.last.update(author: nil)
Author.last.books_count

Expected behavior

Author.last.books_count should be equal to 2.

Actual behavior

Author.last.books_count equal to 1.

The query below executed twice:

 UPDATE `authors` SET `books_count` = COALESCE(`books_count`, 0) - 1 WHERE `authors`.`id` = 15

Screenshot with helpful information:
rails_counter_twice

System configuration

Rails version: 5.2.0

Ruby version: 2.5.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions