Acts As Rateable Plugin
Continuing with my work with Ruby on Rails plugins here is my version of the acts_as_rateable plugin. Use this plugin to make your model instances be rated by users. The ratings are numeric and could be from 0 to any number you would like. Typically you can rate articles, posts, reviews, etc from 0 to 5 but this plugin does not dictate the range. To install this plugin run the following command:
script/plugin install http://juixe.com/svn/acts_as_rateable
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 :ratings, :force => true do |t| t.column :rating, :integer, :default => 0 t.column :created_at, :datetime, :null => false t.column :rateable_type, :string, :limit => 15, :default => "", :null => false t.column :rateable_id, :integer, :default => 0, :null => false t.column :user_id, :integer, :default => 0, :null => false end add_index :ratings, ["user_id"], :name => "fk_ratings_user" end def self.down drop_table :ratings end
Once you have the acts_as_rateable plugin installed you can make your ActiveRecord models act as rateable by calling the acts_as_rateable method.
class Post < ActiveRecord::Base acts_as_rateable end
In your controller you can rate a post with just a few lines of code:
post = Post.find(params[:id]) rating = Rating.new(:rating => 2, :submitted => Time.new) @post.ratings << rating
Similarly you can do this:
post = Post.find(params[:id]) post.add_rating Rating.new(:rating => 2)
And of course you can iterate through the ratings of a post by using the ratings property such as the following bit of code:
post.ratings.each { |r| logger << "rating value: #{r.rating} for object: #{r.rateable}\n" }
You can also use the ratings property to get the number of ratings this post has been given.
count = post.ratings.size
And if you want to display the average rating you can use the rating function.
average_rating = post.rating
Stay tuned for more on Ruby on Rails plugins…