ar-async-counter-cache
This gem allows you to update ActiveRecord counter cache columns asynchronously. You may want to do this in situations where you want really speedy inserts and have models that “belong_to” many different parents.
You use it like such:
class User < ActiveRecord::Base
has_many :comments
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user, :async_counter_cache => true
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user, :async_counter_cache => true
belongs_to :post, :async_counter_cache => "count_of_comments"
end
Notice, you may specify the name of the counter cache column just as you can with the normal belongs_to :counter_cache option. You also may not use both the :async_counter_cache and :counter_cache options in the same belongs_to call.
All you should need to do is require this gem in your project that uses ActiveRecord and you should be good to go;
e.g. In your Gemfile:
gem 'ar-async-counter-cache', '0.0.1'
and then in RAILS_ROOT/config/environment.rb somewhere:
require 'ar-async-counter-cache'
This gem has built-in support for Resque (github.com/defunkt/resque). Al you need is resque in your loadpath:
e.g. In your Gemfile:
gem 'resque', '1.9.4'
By default, the Resque job is placed on the :counter_caches queue:
@queue = :counter_caches
However, you can change this:
in RAILS_ROOT/config/environment.rb somewhere:
ArAsyncCounterCache.resque_job_queue = :low_priority
If you don’t want to use Resque, you must define one instance method for your models using ar-async-counter-cache:
e.g.:
Comment#async_increment_counters
That method should pass a message onto a queue for a background processor to handle later. That background processor should call:
Comment#update_async_counters(:increment)