2

I need to decrease the counter of active users in a group, actually is increasing correctly when a new user pass from inactive to active in the group. But when change from active to inactive and then to active again the counter of active users is one more.

So what I need is to decrease the counter when passing from active to inactive.

Until now I tried to use the delta_magnitude param to make it decrease but didn't work.

This is how it looks the class actually

class GroupUser < ApplicationRecord
    attr_accessor :send_challenge

    belongs_to :group
    belongs_to :user

    counter_culture :group, column_name: proc { |model| model.active? ? 'users_count' : nil },
                                   column_names: {
                                     ['group_users.active = ?', true] => 'users_count'
                                   }

As you can see I use the dynamic-column-names

Here is what I have try so far

class GroupUser < ApplicationRecord
    attr_accessor :send_challenge

    belongs_to :group
    belongs_to :user

    counter_culture :group, column_name: proc { |model| model.active? ? 'users_count' : nil },
                                   column_names: {
                                     ['group_users.active = ?', true] => 'users_count'
                                   },
                                   delta_magnitude: 1

Here I add the delta-magnitude trying to make it decrease but didn't work.

I there a way to express a condition to make it decrease?

2 Answers2

1

At the end I just decrease it manually in the same query that change from active to inactive. If someone knows the correct answer it will be useful next time.

1

If you’re updating the active attribute with normal save that includes callbacks, the current counter_culture version actually recalculate the count on value change. As per the readme:

Updates counter cache when values change, not just when creating and destroying

At the reporting time that might have been a bug, but it should work now.

borisrorsvort
  • 907
  • 7
  • 22