Skip to content

Instantly share code, notes, and snippets.

@sandeepravi
Last active October 5, 2015 16:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandeepravi/2837535 to your computer and use it in GitHub Desktop.
Save sandeepravi/2837535 to your computer and use it in GitHub Desktop.
A Countable Field for Mongoid
class Image
include Mongoid::Document
field :likes_count, :type => Integer, :default => 0
has_many :likes
end
class Like
include Mongoid::Document
include Mongoid::CounterCache
counter_cache :document => "images", :field => "likes_count"
belongs_to :image
end
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
@araslanov-e
Copy link

Typo: :field => "likes_count" in like.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment