acts_as_voteable - Installing and Using the Plugin
Posted by ben, Wed Jan 24 19:24:00 UTC 2007
If you read the original acts_as_voteable post about creating an acts_as plugin for rails then here is the installation instructions I promised. If you didn’t read it, then you have no idea what I am talking about, still here it is.
Installation is easy given the script/plugin command. This automates the svn export of the plugin and manages source repositories of known plugins. Simply run …
script/plugin install http://svn.comthread.com/public/plugins/tags/stable/acts_as_voteable/
That will export the current version to your vendor/plugins/ folder. See script/plugin post to get instructions for removing or updating this plugin. Also, see how to install the plugin from a repository.
Be sure to read the README file included. It has instructions for creating the migration necessary to hold the votes. This is the migration necessary for the current version:
def self.up
create_table :votes do |t|
t.column :voter_id, :integer
t.column :voter_type, :string
t.column :voteable_id, :integer
t.column :voteable_type, :string
t.column :score, :integer
t.column :created_at, :datetime
end
end
def self.down
drop_table :votes
end
To use the plugin simply add the line acts_as_voteable on any ActiveRecord object. For example …
class Widget < ActiveRecord::Base
acts_as_voteable
end
Now we can cast our votes on widgets. You have the following methods available for any object that uses acts_as_voteable:
- vote_for
- vote_abstain
- vote_against
- vote_score
- votes_for
- votes_abstain
- votes_against
- voted?
- vote
The vote_[for/abstain/against] methods all take a voter as a parameter. This is the person or thing casting the vote. It is a ploymorphic association so you can put any type of object you want to in there. It was intended to hold the user that casted the vote. A voter can only cast one vote per object.
The vote_score tallies up all the votes and gives you a score as an integer based on 1 point for votes_for, 0 points for votes_abstain & -1 points for votes_against
The votes_[for/abstain/against] methods all return the total number of votes for that particular sentiment.
The voted? method takes a voter as a parameter and returns a boolean telling if that voter has already cast a vote for that object.
The vote method takes a voter as a parameter and returns the score [1, 0, -1] of that voters vote for the current object and nil if there is no vote.
Also, you can call votes to return all of the votes for an object since the association is joined as votes.