Acts As Voteable Rails Plugin
Right on the heels of my release of acts_as_commentable, I am now making available a acts_as_voteable Ruby on Rails plugin. The Acts As Voteable plugin allows for model to be voted on by users.
To install this plugin run the following command:
script/plugin install http://juixe.com/svn/acts_as_voteable
The installation process will add several ruby files in the vendor/plugins directory. Create a new rails migration and cut and past the following self.up and self.down methods:
def self.up create_table :votes, :force => true do |t| t.column :vote, :boolean, :default => false t.column :created_at, :datetime, :null => false t.column :voteable_type, :string, :limit => 15, :default => "", :null => false t.column :voteable_id, :integer, :default => 0, :null => false t.column :user_id, :integer, :default => 0, :null => false end add_index :votes, ["user_id"], :name => "fk_votes_user" end def self.down drop_table :votes end
Once you have installed the plugin you can start using it in your ActiveRecord models simply by calling the acts_as_voteable method.
class Post < ActiveRecord::Base acts_as_voteable end
To cast a vote for a post you can do the following:
vote = Vote.new(:vote => true) post = Post.find(params[:id]) post.votes << vote
ActiveRecord models that act as voteable can be queried for the positive votes, negative votes, and a total vote count by using the votes_for, votes_against, and votes_count methods respectively. Here is an example:
positiveVoteCount = post.votes_for negativeVoteCount = post.votes_against totalVoteCount = post.votes_count
And because the Acts As Voteable plugin will add the has_many votes relationship to your model you can always get all the votes by using the votes property:
allVotes = post.votes
Technorati Tags: ruby, rails, ruby on rails, plugin, rails plugin, acts_as_commentable, acts_as_voteable