Skip to content

Instantly share code, notes, and snippets.

@mrkurt
Created May 14, 2010 14:10
Show Gist options
  • Save mrkurt/401202 to your computer and use it in GitHub Desktop.
Save mrkurt/401202 to your computer and use it in GitHub Desktop.
module Rankable
extend ActiveSupport::Concern
included do
field :ratings_value_sum, :type => Integer, :default => 0
field :ratings_count, :type => Integer, :default => 0
embeds_many :ratings
end
module InstanceMethods
def rating; ratings_value_sum || 0; end
def rated?(user)
user && self.ratings.any?{|r| r.user_id == user.id}
end
def can_rate?(user)
if !user
false
elsif self.respond_to?(:user) && self.user == user
false
elsif rated?(user)
false
else
true
end
end
def rate(user, value = 1)
rating = Rating.new(:value => value)
rating.user = user
rating_params = {
'_id' => self.id,
'ratings' => {'$not' => {'$elemMatch' => {'user_id' => user.id}}}
}
rating_attrs = {
'$push' =>
{'ratings' => rating.raw_attributes},
'$inc' =>
{'ratings_value_sum' => value, 'ratings_count' => 1}
}
result = self.class.collection.update(rating_params, rating_attrs, :safe => true, :muti => false)
result[0][0]['updatedExisting']
end
end
end
class Rating
include Mongoid::Document
field :value, :type => Integer
field :created_at, :type => Time, :default => Time.now
embedded_in :rankable, :inverse_of => :ratings
belongs_to_related :user
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment