Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-3296

counter_cache needs callbacks for relations update

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.0.1
    • Affects Version/s: None
    • Component/s: None
    • None

      (I'm a quite new user and contributor of Mongoid. Hello everyone and thanks for the awesome work! :+1

      In add_counter_cache_callbacks method, the only callbacks that are added are after_create and before_destroy.

      What about when the association is updated?

      In my case, I have 2 models Company and User:

      class User
        include Mongoid::Document
        belongs_to :company, counter_cache: true
      end
      
      class Company
        include Mongoid::Document
        field :users_count, type: Integer, default: 0
        has_many :users
      end
      

      When I update a User to change his Company, the users_count is not updated. The counter for the former Company is not decremented, and the counter for the new Company is not incremented.

      Maybe I missed something, but shouldn't add_counter_cache_callbacks also implement before_update and after_update? or should it rather implement the new Relation Callbacks?

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            spone Hans Lemuet
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: