Last active
October 5, 2015 16:37
-
-
Save sandeepravi/2837535 to your computer and use it in GitHub Desktop.
A Countable Field for Mongoid
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 Image | |
include Mongoid::Document | |
field :likes_count, :type => Integer, :default => 0 | |
has_many :likes | |
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 Like | |
include Mongoid::Document | |
include Mongoid::CounterCache | |
counter_cache :document => "images", :field => "likes_count" | |
belongs_to :image | |
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 | |
# Public: Allows caching of countable Integer data | |
# | |
# args - The Hash args used to select the document and field: | |
# :document - The String document name | |
# :field - The String field name to count | |
# | |
# Examples | |
# | |
# cache_counter :document => "images", :field => "like_count" | |
# => Imaage Object with counter incremented / decremented | |
def counter_cache(args) | |
model = args[:document] | |
field = args[:field] | |
after_create do |document| | |
relation = document.send(model) | |
relation.collection.update(relation._selector, {'$inc' => {field.to_s => 1}}) | |
end | |
after_destroy do |document| | |
relation = document.send(model) | |
relation.collection.update(relation._selector, {'$inc' => {field.to_s => -1}}) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typo:
:field => "likes_count"
inlike.rb