Recently I needed to implement star rating system for one of my project I am working on.

If you are not familiar with a star rating system, its simply a method of voting using (usually) 5 stars in a row, which will change colour as you hover over them indicating the level at which to rate something. You may think a simple rollover would accomplish this but difficulty arises because as you rollover each star it should stay highlighted while you light up the next one and so on until the end of the row of stars.

If this doesnt make much sense to you then take a look at what we are going to achieve in this article. (I will leave the server-side coding to someone more knowledgeable and we will just concentrate on the visual aspects of making this effect happen. )

As you can see from the demo the stars stay hovered as you rollover each one. However, as mentioned earlier, the complicated part is that as each star is hovered it should stay alight while the next one is hovered so that if you start at the left side then 1,2,3,4 and 5 stars will be alight as you traverse the row. Usually a rollover will only be active on the anchor that the pointer is currently over making previous anchors lose their focus and thus their hover effect disappear.

 

Install the acts_as_rateable plugin.

Run the following from the root of your Rails app to install the plugin.


or
http://rubyforge.org/projects/rateableplugin/

Create the table(migration) to store rating into database

Model

models rateable

I was trying to add a rating system for the model Picture. Yours can obviously be whatever you like but from here on out I’ll be using Picture. So add acts_as_rateable to your model.

Controller to handle the rating

Views

Create the partial /views/rating/_rating.rhtml

A little RJS

Create the file /views/rating/rate.rjs

This will replace the star ratings with the partial we created previously in order to reflect any rating changes made by the submission.

Render the partial in one of your views.

This needs @picture(or whatver you’re going to be using) in order to function.

Remember to add the css and image

Image for your CSS

star_rating.gif