Rails 4 Ajax 调用只工作一次

Rails 4 Ajax call only works once

本文关键字:一次 工作 Ajax 调用 Rails      更新时间:2023-09-26

我有一个应用程序,您可以在其中发布Links。每个Link has_many Comments

我已经设置了ajax,用户可以在其中对特定评论投赞成票。目前,用户可以第一次通过 ajax 成功对评论投赞成票,但如果用户随后尝试对同一页面上的不同评论投赞成票,则 ajax 会中断,并且在刷新页面之前不会更新值。

comments_controller.rb:

def comment_upvote
  @comment = Comment.find(params[:id])
  @link = Link.where(id: @comment.link_id)
  @comment.upvote_by current_user
  respond_to do |format|
    format.html {redirect_to link_path(@link)}
    format.js {}
  end
end  

views/comments/_comment.html.erb:

<div class="well">
  <h2><%= comment.title %></h2>
  <p class="text-muted">Added by <strong><%= comment.author %> <%= comment.author_last_name %></strong> on
  <%= l(comment.created_at, format: '%B, %d %Y %H:%M:%S') %></p>
  <blockquote>
    <p><%= comment.body %></p>
  </blockquote>
  <p><%= link_to 'reply', new_comment_path(parent_id: comment.id, link_id: @link.id)  %></p>
  <%= link_to pointup_comment_path(comment.id), method: :put, remote: true do %>
    +
  <% end %>
  <div id="comment-votes">
    Votes: <%= comment.get_upvotes.size %>
  </div>

观点/评论/comment_upvote.js.erb:

$('#comment-votes').html("<%= j render "upvotes", locals: { @comment => @comment } %>")

views/comments/_upvotes.html.erb:

Votes: <%= @comment.get_upvotes.size %>

有没有简单的方法可以解决这个问题?如果您需要额外的详细信息,请告诉我。

这里的问题是有很多div 的 id comment-votes .当你尝试通过id获取元素时,它总是得到相同的div。

要解决此问题,您需要使每个注释的id唯一。

views/comments/_comment.html.erb:

<div id="comment-votes-<%= comment.id %>">
  Votes: <%= comment.get_upvotes.size %>
</div>

设置唯一注释 ID 后。你只需要更改 ajax 调用。

观点/评论/comment_upvote.js.erb:

 $("#comment-votes-<%= @comment.id %>").html("<%= j render "upvotes", locals: { @comment => @comment } %>")