2016-02-15 35 views
0

我有一個應用程序,你可以發佈Links。每Link has_many CommentsRails 4 Ajax調用只能工作一次

我已經設置了一個用戶可以upvote特定評論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 

的意見/評論/ _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 } %>") 

的意見/評論/ _upvotes.html.erb:

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

是否有一個簡單的方法來解決這一問題?讓我知道你是否需要額外的細節。

+0

爲什麼你讓所有的upvotes在一個數組,然後返回數組的大小?爲什麼不運行SQL計數查詢?我在詢問'@ comment.get_upvotes.size' –

+0

我正在使用一個名爲acts_as_votable的投票的寶石,這只是它的API – BillyBib

回答

2

這裏的問題是,有很多div ID爲comment-votes。當你試圖通過id獲得元素時,它總是得到相同的div。

要解決此問題,您需要使每個評論都有唯一的id

的意見/評論/ _comment.html.erb:

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

設置獨特的評論IDS之後。你只需要改變ajax調用。

的意見/評論/ comment_upvote.js.erb:

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

完美。謝謝:) – BillyBib

+0

很高興幫助:) –