繁体   English   中英

Rails 4 Ajax调用仅工作一次

[英]Rails 4 Ajax call only works once

我有一个可以在其中发布Links的应用程序。 每个Link都有多条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 %>

有简单的方法可以解决此问题吗? 让我知道您是否需要其他细节。

这里的问题是,有很多具有id comment-votes div。 当您尝试通过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 } %>")

暂无
暂无

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

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