I created a house scaffold which has many reviews and the reviews can be
voted on. All the reviews for a house are shown on the house show page.
Then each review has a vote button and a display to show the current
number of votes. I would like the vote button to vanish and the vote
count to change by AJAX after each vote.
# reviews/_rev.html.erb
<% @house.reviews.each do |review| %>
posted <%= time_ago_in_words review.created_at %> ago by <%=
review.user.username %> |
<p id='votes'><%= pluralize(review.votes_count, 'vote') %></p>
That doesn't quite work. When I use <%= @review.votes_count %> in the
create.js.erb file it updates the counter on the first review,
regardless of whether the vote was placed on the first review or not.
I thought maybe if I loop through the reviews again the create.js.erb
file it might work.
<% @house.reviews.each do |review| %>
$("#votes").html("<%= review.votes_count %>")
<% end %>
What you currently have will generate HTML that looks like the following if you have 3 reviews:
1 vote
2 votes
3 votes
$(“#votes”).html(“3 votes”)
$(“#votes”).html(“4 votes”)
$(“#votes”).html(“5 votes”)
See the problem?
The problem is that each paragraph tag has the same ID. jQuery will only update the first one. Each paragraph needs to have a unique ID, then your JavaScript to update the paragraph needs to update the specific unique ID.
Including the primary key in the HTML ID is a good solution:
Then your jQuery can update the specific paragraph that it needs to: