0.0
No release in over a year
CounterOne provides improved counter cache for Rails app with support various relationships and conditions.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

 Project Readme

CounterOne

Work in progress, not ready for production

Improved counter cache for Rails app with support various relationships and conditions.

Features

  • Updates the counter cache for create, destroy, and update actions, as well as any single action
  • Counter caches for multi levels and has_one/has_many through relations
  • Conditions for counter caches
  • Recalculating counter caches with conditions

Installation

Add this line to your application's Gemfile:

gem 'counter_one'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install counter_one

Usage

Counter cache for simple relation

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
  counter_one :user
end

It will be keep up to date products_count for users when product is created or destroyed.

Counter cache for multi levels relation

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :product
  counter_one [:product, :user]
end

It will be keep up to date comments_count for users when comment is created or destroyed.

Counter cache for has_one through relation

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :product
  has_one :user, through: :product

  counter_one :user
end

Counter cache with custom counter field

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
  counter_one :user, column: :custom_counter
end

Counter cache with conditions

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
  counter_one :user, column: :active_products, only: ->(product) { product.active? }
end

Counter cache only for deleted records

class User < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :user
  counter_one :user, column: :deleted_products, on: [:destroy]
end

License

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