AJAX更新微博投票上/下部分只刷新最新的post

使用Rails 3,JRuby。

我希望为我的Rails社交应用程序添加“投票”和“投票结果”评级,允许用户基本上喜欢和不喜欢post。 这非常有效,但无论何时投票,都会刷新整个页面。 为了解决这个问题,我想实现一个部分刷新,它只会在post提要中更新特定的post得分。

我遵循我的惯常模式来实现AJAX部分刷新,但是,结果并不是我想到的。 而不是刷新我喜欢/不喜欢的post,它刷新最近的post与我刚刚喜欢/不喜欢的post的新分数。

我已经将此识别为部分刷新问题,因为当我手动刷新整个页面时,每个post都有正确的喜欢/不喜欢的分数(包括我打算改变的那个)。 我认为问题与我的页面使用“do block”将post呈现到页面的方式有关。 我的问题是,我无法弄清楚如何获得正确刷新我投票的微博所需的行为。 这是我的一些代码:

_micropost.html.erb(部分)

 
Post <%= link_to ''.html_safe, '#', class: "comment_link pull-right"%> <%= link_to ''.html_safe, increment_micropost_path(mp.id), class: "comment_link pull-right", :remote => true%> <%= link_to ''.html_safe, decrement_micropost_path(mp.id), class: "comment_link pull-right", :remote => true %>
'microposts/rating', :locals => {:micro => mp} %>
(....)

_home.html.erb

 (....) 
'microposts/micropost', :locals => {:microposts => @microposts }, :remote => true %>
(....)

我的_rating.html.erb部分(显示信息的位)

  

控制器(我只是显示增量方法,它们几乎相同

 #increments micropost rating by 1 def increment @micropost = Micropost.find(params[:id]) @increment = lambda { |micropost| micropost.update_attribute(:rating, micropost.rating.to_i + 1) } @increment.call @micropost respond_to do |format| format.html {redirect_to root_url} format.js end end 

和相应的increment.js.html

 $('#global').html(" 'microposts/rating', :locals => {:micro => @micropost} %>"); 

我在上面提到过,微博的实际递增/递减function很好 – 它只是使用不符合预期的AJAX重新渲染这些信息。 任何想法,请分享。

原因是您的代码中有多个div#global (因为each循环),因此浏览器只能识别第一个。 将global从id更改为类,然后它应该工作。 我还要为div添加一个data-num属性,并为其分配数据库对象的id (不要与HTML id混淆)。 像这样的东西:

 
<%= render :partial => 'microposts/rating', :locals => {:micro => mp} %>

然后,在您的increment.js.erb (我认为您的意思是代替.js.html …),将其更改为:

 $('div.global[data-num="<%= @micropost.id %>"]').html("<%= escape_javascript render :partial => 'microposts/rating', :locals => {:micro => @micropost} %>"); 

这样,JavaScript将始终知道要更新哪一个,因为它基于数据库ID。