Rails Ajax rating system (Part 1) 1 comment

Posted by stephane Sun, 18 Mar 2007 11:12:00 GMT

Needed for a little project, I found a plugin: “acts_as_rated”.

“Adds rating capabilities to any ActiveRecord object. It has the ability to work with objects that have or don’t special fields to keep a tally of the ratings and number of votes for each object. In addition it will by default use the User model as the rater object and keep the ratings per-user. It can be configured to use another class, or not use a rater at all, just keeping a global rating”

Not yet released as gem please checkout the following trunk : svn://rubyforge.org/var/svn/acts-as-rated/trunk/acts_as_rated

Installation:

script/plugin install svn://rubyforge.org/var/svn/acts-as-rated/trunk/acts_as_rated

Generate the Rating model:

The rater is User (by default) and rated object is Photo

script/generate migration add_rating
migration/01_add_rating.rb
class AddRating < ActiveRecord::Migration

    def self.up
      ActiveRecord::Base.create_ratings_table
      Photo.add_ratings_columns
    end

    def self.down
      # Remove the added columns
      Photo.remove_ratings_columns
      ActiveRecord::Base.drop_ratings_table
    end

  end
rake db:migrate

Add table ratings and columns rating_count, rating_total, rating_avg to the Photos table.

Usage:

class Photo < ActiveRecord::Base
  acts_as_rated :rating_range => 0..5
end

stephane = User.find_by_username("stephane")
picture = Photo.new("beautiful picture")
picture.rate 4, stephane

that’s all for now … (Next: integrate CSS rating interface)

Trackbacks

Use the following link to trackback from your own site:
http://www.rubynaut.net/articles/trackback/14164

Comments

Leave a response

  1. carlivar 3 months later:

    Where’s Part 2?

Comments