0.0
No commit activity in last 3 years
No release in over 3 years
Counter cache for ActiveRecord
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 1.17
~> 10.0
~> 3.0
 Project Readme

Counter Cache for ActiveRecord

Installation

Add this line to your application's Gemfile:

gem 'counter_cache'

And then execute:

$ bundle

Or install it yourself as:

$ gem install counter_cache

Usage

For example models

Item model: models/item.rb

  class Item < ActiveRecord::Base
  
    belongs_to :list
    
    scope :published, -> { where(status: :published) }
  
  end

Basic

  belongs_to :list
  counter_cache :list

Or by ActiveRecord supported

  belongs_to :list, counter_cache: true

We will caching to items_count column in lists table

Advanced

With scope option
  • By model scopes
  counter_cache :list, scope: :published
  • By where hash
  counter_cache :list, scope: { status: :published }
  • By where string
  counter_cache :list, scope: "status = 'published'"
With column option
  • Set column name to caching
  counter_cache :list, column: :custom_name

Default column name to cached is append _count to self table name

=> items + _count

With column vs scope options
  counter_cache :list, scope: :published, column: :published_items_count
  • Multiple caching
  counter_cache :list, scope: :published, column: :published_items_count
  counter_cache :list, scope: { status: :rejected }, column: :rejected_items_count

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ThanhKhoaIT/counter_cache. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the CounterCache project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.