简体   繁体   中英

Rails Upvote AJAX not working properly

So my upvote link is replacing the vote counter for all the links instead of the individual one. Help?

Controller

  def upcount
    @category = Category.find(params[:id])
    @category.upcount
    @category.save
    respond_to do |format|
      format.html {redirect_to categories_path(@category)}
      format.js
    end
  end

View

  <% @categories.each do |category| %>
  <div class="col-md-3 col-sm-6 hero-feature">
    <div class="thumbnail">
      <%= image_tag category.image.url(:large) %>
      <div class="caption">
        <%= category.name %> - <%= category.quote %></p>
        <%= link_to "Upvote", upcount_category_path(category), method: "put", remote: true %>
        <div id="total-votes">
          <%= category.count %>
        </div>
      </div>
    </div>
  </div>
  <% end %>

Upcount.js.erb

$("#total-votes").html("<%= @category.count %>")

Clicking the second link will turn the replace the first and second link with 15. Any help is appreciated. Thanks!

HTML ids are meant to be unique. Your duplication of the "total-votes" id is resulting in invalid HTML. It is also confusing your javascript, as it doesn't know which div you want to target.

You can fix this by adding the category id to the html id like total-votes-<%= category.id %> , so that it is unique for all.

Full example:

View file

<% @categories.each do |category| %>
  <div class="col-md-3 col-sm-6 hero-feature">
    <div class="thumbnail">
      <%= image_tag category.image.url(:large) %>
      <div class="caption">
        <%= category.name %> - <%= category.quote %></p>
        <%= link_to "Upvote", upcount_category_path(category), method: "put", remote: true %>
        <div id="total-votes-<%= category.id %>">
          <%= category.count %>
        </div>
      </div>
    </div>
  </div>
  <% end %>

Upcount.js.erb

$("#total-votes-<%= @category.id %>").html("<%= @category.count %>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM