Turbo-charged counter caches for your Rails app.
Turbo-charged counter caches for your Rails app.
Turbo-charged counter caches for your Rails app. Huge improvements over the Rails standard counter caches:
Tested against Ruby 3.0, 3.1, 3.2, 3.3 and 4.0 and against the latest patch releases of Rails 6.0, 6.1, 7.0, 7.1, 7.2, 8.0 and 8.1.
Please note that -- unlike Rails' built-in counter-caches -- counter_culture does not currently change the behavior of the .size method on ActiveRecord associations. If you want to avoid a database query and read the cached value, please use the attribute name containing the counter cache directly.
product.categories.size # => will lead to a SELECT COUNT(*) query
product.categories_count # => will use counter cache without queryAdd counter_culture to your Gemfile:
gem 'counter_culture', '~> 3.2'Then run bundle install
You must create the necessary columns for all counter caches. You can use counter_culture's generator to create a skeleton migration:
rails generate counter_culture Category products_countWhich will generate a migration with code like the following:
add_column :categories, :products_count, :integer, null: false, default: 0Note that the column must be NOT NULL and have a default of zero for this gem to work correctly.
If you are adding counter caches to existing data, you must add code to manually populate their values to the generated migration.
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category
end
class Category < ActiveRecord::Base
has_many :products
endNow, the Category model will keep an up-to-date counter-cache in the products_count column of the categories table.
class User < ActiveRecord::Base
has_many :group_memberships
has_many :groups, through: :group_memberships
end
class Group < ActiveRecord::Base
has_many :group_memberships
has_many :members, through: :group_memberships, class: "User"
end
class GroupMembership < ActiveRecord::Base
belongs_to :group
belongs_to :member, class: "User"
counter_culture :group, column_name: "members_count"
# If you'd like to also touch the group when `members_count` is updated
# counter_culture :group, column_name: "members_count", touch: true
endNow, the Group model will have an up to date count of its members in the members_count column
class Product < ActiveRecord::Base
belongs_to :sub_category
counter_culture [:sub_category, :category]
end
class SubCategory < ActiveRecord::Base
has_many :products
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :sub_categories
endNow, the Category model will keep an up-to-date counter-cache in the products_count column of the categories table. This will work with any number of levels.
If you want to have a counter-cache for each level of your hierarchy, then you must add a separate counter cache for each level. In the above example, if you wanted a count of products for each category and sub_category you would change the Product class to:
class Product < ActiveRecord::Base
belongs_to :sub_category
counter_culture [:sub_category, :category]
counter_culture [:sub_category]
endclass Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: "products_counter_cache"
end
class Category < ActiveRecord::Base
has_many :products
endNow, the Category model will keep an up-to-date counter-cache in the products_counter_cache column of the categories table. This will also work with multi-level counter caches.
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: proc {|model| "#{model.product_type}_count" }
# attribute product_type may be one of ['awesome', 'sucky']
end
class Category < ActiveRecord::Base
has_many :products
endclass Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: :weight, delta_magnitude: proc {|model| model.product_type == 'awesome' ? 2 : 1 }
end
class Category < ActiveRecord::Base
has_many :products
endNow the Category model will keep the weight column up to date: awesome products will affect it by a magnitude of 2, others by a magnitude of 1.
You can also use a static multiplier as the delta_magnitude:
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: :weight, delta_magnitude: 3
end
class Category < ActiveRecord::Base
has_many :products
endNow adding a Product will increase the weight column in its Category by 3; deleting it will decrease it by 3.
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: proc {|model| model.special? ? 'special_count' : nil }
end
class Category < ActiveRecord::Base
has_many :products
endNow, the Category model will keep the counter cache in special_count up-to-date. Only products where special? returns true will affect the special_count.
If you would like to use this with counter_culture_fix_counts, make sure to also provide the column_names configuration.
If you would like to temporarily pause counter_culture, for example in a backfill script, you can do so as follows:
Review.skip_counter_culture_updates do
user.reviews.create!
end
user.reviews_count # => unchangedInstead of keeping a running count, you may want to automatically track a running total.
In that case, the target counter will change by the value in the totaled field instead of changing by exactly 1 each time.
Use the :delta_column option to specify that the counter should change by the value of a specific field in the counted object.
For example, suppose the Product model table has a field named weight_ounces, and you want to keep a running
total of the weight for all the products in the Category model's product_weight_ounces field:
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, column_name: 'product_weight_ounces', delta_column: 'weight_ounces'
end
class Category < ActiveRecord::Base
has_many :products
endNow, the Category model will keep the counter cache in product_weight_ounces up-to-date.
The value in the counter cache will be the sum of the weight_ounces values in each of the associated Product records.
The :delta_column option supports all numeric column types, not just :integer. Specifically, :float is supported and tested.
class Product < ActiveRecord::Base
belongs_to :category
counter_culture :category, foreign_key_values:
proc {|category_id| [category_id, Category.find_by(id: category_id)&.parent_category&.id] }
end
class Category < ActiveRecord::Base
belongs_to :parent_category, class_name: 'Category', foreign_key: 'parent_id'
has_many :children, class_name: 'Category', foreign_key: 'parent_id'
has_many :products
endNow, the Category model will keep an up-to-date counter-cache in the products_count column of the categories table. Each product will affect the counts of both its immediate category and that category's parent. This will work with any number of levels.
By default, counter_culture does not update the timestamp of models when it updates their counter caches. If you would like every change in the counter cache column to result in an updated timestamp, simply set the touch option to true:
counter_culture :category, touch: trueThis is useful when you require your caches to get invalidated when the counter cache changes.
You may also specify a custom timestamp column that gets updated only when a particular counter cache changes:
counter_culture :category, touch: 'category_count_changed'With this option, any time the category_counter_cache changes both the category_count_changed and updated_at columns will get updated.
Some applications run into issues with deadlocks involving counter cache updates when using this gem. See #263 for information and helpful links on how to avoid this issue.
Another option is to simply defer the update of counter caches to outside of the transaction. This gives up transactional guarantees for your counter cache updates but should resolve any deadlocks you experience. This behavior is disabled by default, enable it on each affected counter cache as follows:
counter_culture :category, execute_after_commit: true[NOTE] On Rails 7.2 and newer this uses the built-in ActiveRecord.after_all_transactions_commit API and requires no extra dependencies. On older Rails versions you need to manually specify the after_commit_action gem as a dependency in your Gemfile to use this feature:
...
gem "after_commit_action"
...You can also pass a Proc for dynamic control. This is useful for temporarily moving the counter cache update inside of the transaction:
counter_culture :category, execute_after_commit: proc { !Thread.current[:update_counter_cache_in_transaction] }NOTE: This does not have an effect on Papertrail callbacks
By default, every create/update/destroy will trigger separate UPDATE SQLs for each action and targeted column. For example, if the creation of 1 record needs to increment 3 counter cache columns, a transaction that creates 3 records of this kind will generate 9 UPDATE SQL queries adding +1 to the value of said columns (3 created records x 3 counter cache columns to be incremented by each).
To avoid this, you can wrap the logic that creates/updates/destroys multiple records in CounterCulture.aggregate_counter_updates. This will sum all updates for counter cache columns and will take the latest value for timestamp updates. As a result, you will get just one UPDATE SQL query per target record that updates all of its columns at once.
COMMITActiveRecord::Base.transaction do
CounterCulture.aggregate_counter_updates do
# list of updates
end # => executes aggregated SQLs
endCOMMITCounterCulture.aggregate_counter_updates do
ActiveRecord::Base.transaction do
# list of updates
end
end # => executes aggregated SQLs-- Before
UPDATE `authors` SET `authors`.`books_count` = COALESCE(`authors`.`books_count`, 0) + 1 WHERE `authors`.`id` = 1
UPDATE `authors` SET `authors`.`books_count` = COALESCE(`authors`.`books_count`, 0) + 1 WHERE `authors`.`id` = 1
UPDATE `authors` SET `authors`.`boNo open issues yet, or sync has not completed.