Specification

Clicking a star rating turns on the stars to the left of the star I clicked.
Clicking a star submits the star rating.
When I refresh the page, the star ratings should be persistent.

We’ll be using Rails’ functions including:

form_for
hidden_field
Rails Helpers

We’ll be using jQuery functions including:

click
each
ajax


<% formid = "movie#{movie.id}_rating" %>
<%= form_for movie.ratings.last || movie.ratings.build, :html => {:id => form_id , :class => "star_rating_form"} do |f| %>
<%= f.hidden_field :movie_id %>
<%= f.hidden_field :stars, :id => form_id + "_stars" %>
<% end %>
<% (1..5).each do |i| %>

  • <% end %>


    var set_stars = function(form_id, stars) {
    for(i=1; i <= 5; i++){
    if(i <= stars){
    $('#' + formid + '' + i).addClass("on");
    } else {
    $('#' + formid + '' + i).removeClass("on");
    }
    }
    }

    $(function() {
    $('.rating_star').click(function() {
    var star = $(this);
    var form_id = star.attr("data-form-id");
    var stars = star.attr("data-stars");

    $('#' + form_id + '_stars').val(stars);

    $.ajax({
    type: "post",
    url: $('#' + form_id).attr('action'),
    data: $('#' + form_id).serialize()
    })
    });

    $('.star_rating_form').each(function() {
    var form_id = $(this).attr('id');
    set_stars(form_id, $('#' + form_id + '_stars').val());
    });
    });