0.0
No commit activity in last 3 years
No release in over 3 years
ActiveRecord counter_cache has been reborn, with ability to specify conditions.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

 Project Readme

HasCounterOn

ActiveRecord counter_cache has been reborn, with ability to specify conditions. Inspired by counter_cache_with_conditions gem.

Installation

To use it, add it to your Gemfile:

gem 'has_counter_on'

and bundle:

$ bundle install

After Installation

Install migrations

rake has_counter_on:setup

Review the generated migrations then migrate:

rake db:migrate

Usage

Let's say you have a User model and an Article model.

class User < ActiveRecord::Base
  has_many :articles
  has_many :published_articles, -> { where(has_published: true) }, class_name: :Article
end

class Article < ActiveRecord::Base
  belongs_to :user
end

By using ActiveRecord's counter_cache, articles_count can be created as follows: (However, you cannot handle published_articles_count)

class User < ActiveRecord::Base
  has_many :articles
  has_many :published_articles, -> { where(has_published: true) }, class_name: :Article
end

class Article < ActiveRecord::Base
  belongs_to :user, counter_cache: true
end

with has_counter_on, you can handle both of counters like this:

class User < ActiveRecord::Base
  has_many :articles
  has_many :published_articles, -> { where(has_published: true) }, class_name: :Article

  has_counter_on :articles
  has_counter_on :articles, :published_articles_count, has_published: true
end

class Article < ActiveRecord::Base
  belongs_to :user
end

Each counter will be updated automatically like that of the ActiveRecord.

Complex Conditions

Complex conditions can be expressed as lambda.

class User < ActiveRecord::Base
  has_many :articles
  has_many :published_articles, -> { where.not(published_at: nil) }, class_name: :Article

  has_counter_on :articles
  has_counter_on :articles, :published_articles_count, published_at: -> (value) { value.present? }
end

class Article < ActiveRecord::Base
  belongs_to :user
end

Of course, multiple conditions are available.

class User < ActiveRecord::Base
  has_counter_on :articles, :featured_articles_count, has_featured: true, has_published: true
end

Contributing

Bug reports and pull requests are welcome on GitHub.

License

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