简体   繁体   English

Rails Upvote AJAX无法正常工作

[英]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 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. 单击第二个链接将把第一个和第二个链接替换为15。感谢您的帮助。 Thanks! 谢谢!

HTML ids are meant to be unique. HTML ID是唯一的。 Your duplication of the "total-votes" id is resulting in invalid HTML. 您重复填写的“投票总数” ID导致HTML无效。 It is also confusing your javascript, as it doesn't know which div you want to target. 这也使您的JavaScript感到困惑,因为它不知道您要定位的div。

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. 您可以通过将类别ID添加到html ID来解决此问题,例如total-votes-<%= category.id %> ,这样它对于所有人来说都是唯一的。

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 Upcount.js.erb

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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