In this tutorial I will show you how to add ratings to your models by using the acts_as_rateable plugin in Ruby on Rails. This plugin makes ActiveRecord models rateable through a polymorphic association and optionally logs which user rated which model.

Install Plugin

Firstly download the plugin via Github. You may simply click download and extract it into your /vendor/plugins/ directory or if you have git installed, install the plugin via the script:

ruby script/plugin install git://github.com/azabaj/acts_as_rateable.git

Once the plugin is installed, add the following line to your model. In this example I will be adding ratings to a Movie.

class Movie < ActiveRecord::Base
  acts_as_rateable
end

Database

Create a migration for the tables needed for the plugin:

class CreateRatings< ActiveRecord::Migration
  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
end

Usage

Now your model is extended by the plugin, you can rate it calculate the average rating. You can rate your object using integers from 1-xxx.

 # Rate movie with score of 4
@movie.rate_it( 4, current_user.id )
# Get the average rating for the movie.
@movie.average_rating 
# Round off the average rating
@movie.average_rating_round
# Get the average rating in percentage
@movie.average_rating_percent
# Check if movie has been rated by current user
@movie.rated_by?( current_user )
# Find movies with average rating of 4
Movie.find_average_of( 4 )