Skip to content

Instantly share code, notes, and snippets.

@kaievns
Created December 12, 2011 08:59
Show Gist options
  • Save kaievns/1466051 to your computer and use it in GitHub Desktop.
Save kaievns/1466051 to your computer and use it in GitHub Desktop.
MongoID counter_cache hack
#
# Save this in `lib/mongoid/counter_cache.rb`
#
# Then define your relations kinda like that
#
# class Comment
# belongs_to :post, counter_cache: true # 'comments_count'
# belongs_to :user, counter_cache: 'my_field_name'
# end
#
module Mongoid
module CounterCache
def self.included(base)
base.instance_eval do
def belongs_to(name, options = {}, &block)
if counter_field = options.delete(:counter_cache)
counter_cache name.to_s, counter_field == true ? nil : counter_field.to_s
end
super name, options, &block
end
end
end
extend ActiveSupport::Concern
module ClassMethods
def counter_cache(name, counter_field=nil)
counter_field ||= self.name.underscore.pluralize + "_count"
Object.const_get(name.capitalize.camelcase).instance_eval do
field counter_field.to_sym, type: Integer, default: 0
index counter_field.to_sym
end
after_create do |document|
document.send(name).inc(counter_field.to_sym, 1)
end
after_destroy do |document|
document.send(name).inc(counter_field.to_sym, -1)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment