Voteable Mongoid allows you to make your Mongoid::Document objects voteable (up or down). For instance, in a forum, a user can vote up (or down) on a post or a comment.
Voteable Mongoid is built for speed. It minimizes vote data storage and uses only one database request per collection to do both data validation and data update.
Sample app at github.com/vinova/simple_qa
To install the gem, add this to your Gemfile
After that, remember to run “bundle install”
Making Post and Comment voteable, User being the voter
class Post include Mongoid::Document include Mongoid::Voteable # set points for each vote voteable self, :up => +1, :down => -1 references_many :comments end
require 'post' class Comment include Mongoid::Document include Mongoid::Voteable referenced_in :post voteable self, :up => +1, :down => -3 # each vote on a comment can affect votes count and point of the related post as well voteable Post, :up => +2, :down => -1 end
class User include Mongoid::Document include Mongoid::Voter end
Making a vote
@user.vote(@post, :up) # is equivalent to @post.vote(:voter_id => @user.id, :value => :up) # this will affect @post.votes_count and @post.votes_point as well @user.vote(@comment, :down)
Getting votes count and points
puts @post.votes_point puts @post.votes_count puts @post.up_votes_count puts @post.down_votes_count
Getting the list of voted objects of a class
Post.voted_by(@user) Post.up_voted_by(@user) Post.down_voted_by(@user)
Undo a vote
Re-generate counters and vote points in case you change :up / :down vote points
Set counters and point to 0 for uninitialized voteable objects in order sort and query
Migrate from version < 0.6.0
Alex N. - Author
Stefan N. - Unvoting
Copyright © 2010-2011 Vinova Pte Ltd (vinova.sg)
Licensed under the MIT license.