Plugins - Vote Fu
Add to favoritesvote_fu
Allows an arbitrary number of entites (including Users) to vote on models. Adapted from actas_voteable. Differences from actsas_voteable include:
- You can specify the model name that initiates votes.
- You can, with a little tuning, have more than one entity type vote on more than one model type.
- Adds "acts_as_voter" behavior to the initiator of votes.
- Introduces some newer Rails features like named_scope and :polymorphic keywords
Install
Run the following command:
./script/plugin install git://github.com/peteonrails/vote_fu.git
Create a new rails migration using the generator:
./script/generate voteable
Usage
Make your ActiveRecord model act as voteable.
class Model < ActiveRecord::Base acts_as_voteable end
Make your ActiveRecord model(s) that vote act as voter.
class User < ActiveRecord::Base acts_as_voter end
class Robot < ActiveRecord::Base acts_as_voter end
To cast a vote for a Model you can do the following:
Shorthand syntax
voter.vote_for(voteable) # Adds a +1 vote voter.vote_against(voteable) # Adds a -1 vote voter.vote(voteable, t_or_f) # Adds either +1 or -1 vote true => +1, false => -1
ActsAsVoteable syntax
The old acts_as_voteable syntax is still supported:
vote = Vote.new(:vote => true) m = Model.find(params[:id]) m.votes << vote user.votes << vote
Querying votes
ActiveRecord models that act as voteable can be queried for the positive votes, negative votes, and a total vote count by using the votesfor, votesagainst, and votes_count methods respectively. Here is an example:
positiveVoteCount = m.votes_for negativeVoteCount = m.votes_against totalVoteCount = m.votes_count
And because the Vote Fu plugin will add the has_many votes relationship to your model you can always get all the votes by using the votes property:
allVotes = m.votes
The mixin also provides these methods:
voter.voted_for?(voteable) # True if the voter voted for this object. voter.vote_count([true|false|"all"]) # returns the count of +1, -1, or all votes
voteable.voted_by?(voter) # True if the voter voted for this object. @voters = voteable.voterswhovoted
Named Scopes
The Vote model has several named scopes you can use to find vote details:
@petevotes = Vote.forvoter(pete) @postvotes = Vote.forvoteable(post) @recent_votes = Vote.recent(1.day.ago) @descending_votes = Vote.descending
You can chain these together to make interesting queries:
Show all of Pete's recent votes for a certain Post, in descending order (newest first)
@peterecentvoteson_post = Vote.forvoter(pete).for_voteable(post).recent(7.days.ago).descending
Credits
Juixe - The original ActsAsVoteable plugin inspired this code.
Xelipe - This plugin is heavily influenced by Acts As Commentable.
http://blog.peteonrails.com/vote-fu/
git://github.com/peteonrails/vote_fu.git
Rails' (MIT)
Misc. Enhancements
