dxo
dxo

Reputation: 33

ruby on rails: stars specified by js are not displayed

Currently I am doing displaying star_rate as below, but, after all, posts from the second star_rate and beyond are not displayed. Why is this? please tell me!

<% @listings.each do |listing| %>
  <div class="card w-75">
    <div class="card-block">
      <div id="average_star_rate"></div>
    </div>
  </div>
  <hr />
  <script>
    $('#average_star_rate').raty({
      path: '/assets',
      readOnly: true,
      score: <%= listing.average_star_rate %>
    });
  </script>
<% end %>

Upvotes: 0

Views: 44

Answers (1)

max pleaner
max pleaner

Reputation: 26778

There are 2 problems with your code.

First of all, there can only be one element with a given id on a page. Here you are creating many in the loop.

Second, what you are trying to do with the selector is problematic. You are asking it to select all matching elements, but what you really want to select is only the current element of that iteration.

The first problem is easy to resolve. You just change id="average_star_rate" to class="average_star_rate", and lookup .average_star_rate instead of #average_star_rate

The second is not quite so trivial but isn't difficult either. One way to do it is to make a tracker attribute which can be used for lookup. You can add this to the div:

data-id='<%= listing.id %>'

and then change the query to as follows:

$(".average_star_rate[data-id='<%= listing.id %>']").raty({

Upvotes: 1

Related Questions