Counter Cache Rails gem provides an easy way to find and auto-update the number of belonging objects efficiently by caching counters in the parent model.
CounterCache is an alternative for using native Rails counter cache.
My motivation behind this gem is an attempt to separate counting objects from
belongs_to
association. If you prefer counting objects and associations
separated, this gem gives you a clear distinction between defining counter
caches and its associations.
This gem also tends to encapsulate defining counters on the parent model, rather its belonging, so it's clear which counters are specified in every model.
Rails > 5
Add this line to your application's Gemfile:
gem 'counter_cache'
And then execute:
$ bundle
Or install it yourself as:
$ gem install counter_cache
Adding counter_for
macro in Active Record models will generate update
associated counters from belongings models.
Ex:
class Invoice < ApplicationRecord
has_many :line_items
counter_for :line_items
end
counter_for :line_items
assumes the that there is a LineItem
model, and it
will associate the counters in line_items_count
column.
You can either add your counters to your parent table manually.
Note: Your column name should end with _count
Ex:
counter_for :comments
# column name should be comments_count
Or you can use the custom generator provided by this gem:
rails g counter_cache:add_counters [model name] [counter_for option]
rails g counter_cache:add_counters invoice line_items
This will create a new migration for adding an integer line_items_count
column in invoices
table with 0
as default value.
Then run rails db:migrate
.
counter_cached_columns
will return all the cached columns defined per model:
Invoice.counter_cached_columns
#=> [:line_items]
If you want to use another name, you need to use class_name option passing the original model name
Ex:
class Invoice < ApplicationRecord
has_many :line_items
counter_for :items, class_name: :LineItem
end
class Post < ApplicationRecord
counter_for :comments
counter_for :liked_comments, class_name: :Comment, scope: -> { liked? }
end
See the open issues for a list of proposed features
The gem is available as open source under the terms of the MIT License.
The gem is fully tested with minitest You can run the tests with:
rake test
- Muhammad
Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (git checkout -b feature/AmazingFeature)
- Commit your Changes (git commit -m 'Add some AmazingFeature')
- Push to the Branch (git push origin feature/AmazingFeature)
- Open a Pull Request