2013-10-19 65 views
0

我有一個包含多個帖子的頁面。我希望每個帖子的投票在用戶投票後更新,而不必重新加載頁面。我看了看,但大多數遇到此問題的人在頁面上只有一個部分,因此他們只能使用包含div的部分的ID。Rails - 在包含多個部分的頁面上更新單個部分

我試過使用Ajax和jQuery,但仍然遇到問題。現在,投票正確更新,但它改變了一個鏈接上的所有部分。我試着爲每個部分設置一個動態ID,但它只是改變了第一個,因爲@post變量被設置爲最後一個帖子。所以,即使我投了第三篇文章,第一篇文章的部分內容也會改變,而不是第三篇。

我在軌道上3.2.14和Ruby 2.0

這裏是我的代碼:

帖子/ index.html.erb

<% all_posts.each do |post| %> 
    <div class="votes-box"> 
    <%= render partial: 'vote', locals: {post: post} %> 
    </div> 
<% end %> 

帖子/ _vote.html.erb

<%= link_to '', vote_post_path(post, type: 'up'), remote: true, method: 'post', class: 'upvote' %> 
<div class="vote-rep"><%= post.reputation_for(:votes).to_i %> Rep</div> 
<%= link_to '', vote_post_path(post, type: 'down'), remote: true, method: 'post', class: 'downvote' %> 

vote.js.erb

$(".votes-box").html("<%= escape_javascript(render partial: 'vote', locals: {post: @post}).html_safe %>"); 

posts_controller.rb

def vote 
    value = params[:type] == 'up' ? 1 : -1 
    @post = Post.find(params[:id]) 
    @post.add_or_update_evaluation(:votes, value, current_user) 
    respond_to do |format| 
    format.js 
    end 
end 

回答

1

,關鍵是要在HTML先加id來每個崗位,然後只更新JS所需ID響應。

在第一

<% all_posts.each do |post| %> 
    <%# Or you can use `content_tag_for` %> 
    <%# in following line to generate id automatically. %> 
    <div id="post_#{post.id}"> 
    <div class="votes-box"> 
     <%= render partial: 'vote', locals: {post: post} %> 
    </div> 
    </div> 
<% end %> 

然後響應JS

$("#post_#{post.id} .votes-box").html("<%= escape_javascript(render partial: 'vote', 
              locals: {post: @post}).html_safe %>"); 
+0

我試過了,雖然得到了添加了投票,部分沒有改變模板。我也嘗試使用<%%>運營商(而不是#{}),這也沒有幫助。 – user2853185

+0

如果你可以更新DOM以前的所有帖子,你應該沒有問題。請檢查服務器響應是否正確,如果它們是js代碼,請將其粘貼到瀏覽器控制檯中並嘗試。 –

+0

我明白了。我在js文件中使用了「post _ <%= post.id%>」和「#post _ <%= @ post.id%>」。謝謝您的幫助! – user2853185