Skip to content

Unexpected counter_cache results with nested attributes #33113

@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, counter_cache: true

  accepts_nested_attributes_for :author
end

Then:

Book.create(title: 'book 1', author_attributes: { name: 'author 1' })
Book.last.update(author_attributes: { name: 'author 2' })
Author.last.books_count

Expected behavior

Author.last.books_count should be equal to 1.
This is how it works when you update book author using this way:

Book.last.update(author: Author.create(name: 'author 3'))

Actual behavior

Author.last.books_count equal to 0.

Screenshot with helpful information:
rails_counter_bug

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