In my project I want to use a rating system http://www.jqueryrain.com/?SGgGB_oZ I have successfully added it to my project, and it works. I have 2 models: Casino & Rating. Casino has_many :ratings
, and Rating belongs_to :casino
. On my casino index page I want to display the rating system for each casino. This is my view:
<h1>List of casinos</h1>
<div class="casinos-list">
<% @casinos.each do |casino| %>
<div class="casino-item">
<p class="casino-name"><%= link_to casino.name, casino %></p>
<p class="casino-description"><%= casino.description %></p>
<ul class="rating">
<% form_id = "casino_#{casino.id}_rating" %>
<%= form_for casino.ratings.last || casino.ratings.build, html:
{ id: "casino_#{casino.id}_rating", class: 'star_rating_form' } do |f| %>
<%= f.hidden_field :casino_id %>
<%= f.hidden_field :score, id: "#{form_id}_stars", class: 'star-value' %>
<% end %>
</ul>
<div id="<%= "average_rating_#{form_id}" %>"><%= casino.average_rating.to_f %></div>
<div id="<%= "rate_#{casino.id}" %>" class="rateit" data-rateit-mode="font">
</div>
</div>
<% end %>
</div>
My application.js
:
$(document).on('turbolinks:load', function () {
$('.rateit-reset').remove();
$('.rateit-hover').click(function () {
var rating = $(this).parents().attr('aria-valuenow');
var float_number = parseFloat(rating);
var rating_form_input = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').children('.star-value');
var form_id = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').attr('id');
rating_form_input.val(float_number);
$.ajax({
type: 'post',
url: $('#' + form_id).attr('action'),
data: $('#' + form_id).serialize()
});
});
});
And it works, saving the proper value to db, but, as you can see, I use here form_for casino.ratings.last
. I need to add a new rating to the array of ratings, but not to change the last one. Any ideas how should I do it? Thanks.
If you want just add a new rating, remove
casino.ratings.last
. keep onlycasino.ratings.build