Created
July 14, 2011 11:49
-
-
Save a-chernykh/1082313 to your computer and use it in GitHub Desktop.
Mongoid counter cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Forum | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
field :posts_count, :type => Integer, :default => 0 | |
has_many_related :posts | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module CounterCache | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def counter_cache(options) | |
name = options[:name] | |
counter_field = options[:field] | |
after_create do |document| | |
relation = document.send(name) | |
relation.collection.update(relation._selector, {'$inc' => {counter_field.to_s => 1}}, {:multi => true}) | |
end | |
after_destroy do |document| | |
relation = document.send(name) | |
relation.collection.update(relation._selector, {'$inc' => {counter_field.to_s => -1}}, {:multi => true}) | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
include Mongoid::CounterCache | |
counter_cache :name => 'forum', :field => 'posts_count' | |
belongs_to_related :forum | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added mine to config/initializers as I wanted it autoloaded / included for all