![](/img/trans.png)
[英]Calling ajax:beforeSend and ajax:complete on any link_to where remote is true ruby on rails
[英]Rails link_to with ajax remote true not updating view
我有一個有事件的小應用程序。 在事件的索引視圖中,我遍歷所有事件並顯示一些數據。 在each
循環中,我都有一個指向“ Upvote”特定事件的鏈接,這是一個ajax請求。 由於某些原因,我的視圖不會立即更新,但是當我再次單擊“ Upvote”時會更新。
這是我指向“ Upvote”的鏈接
<div id="upvote_link_<%= event.id%>">
<%= link_to('Upvote', upvote_event_path(event), method: :post, remote: true)%>
</div>
這是我upvote
,我遞增法votes
現場。
def upvote
@event = Event.find(params[:id])
Event.increment_counter(:votes, @event.id)
respond_to do |format|
format.js
end
end
接下來是我的upvote.js.erb
,在其中我用新值替換了舊的votes
值。
$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event )%>");
接下來是我的_upvote.html.erb
部分,它替換了舊的votes
值。
<span style="font-family:MetaSerifOT-Book;font-size:13px;">
<%= pluralize(event.votes, "vote") %>
</span>
問題是,當我單擊“ Upvote”鏈接時,我的請求通過了,事件模型中的“ votes
字段得到了更新,但是視圖一直沒有更新,直到我再次單擊“ Upvote
。 我不確定發生了什么。 有什么想法或建議嗎?
更新這是我設置ID的地方: upvotes_<%= event.id %>
我已將部分中的Votes
數隔離了。
<div id="upvotes_<%= event.id%>">
<%= render 'upvote', event: event %>
</div>
問題出在控制器代碼中。 我認為@event對象沒有被重新加載。 一種解決方案是您必須在類似這樣的視圖中重新加載@event對象
$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event.reload )%>");
。
要添加到Santanu
的答案中,您需要查看方法的代碼:
#app/controllers/events_controller.rb
class EventsController < ApplicationController
respond_to :js, only: :upvote #-> if you have the responders gem
def upvote
@event = Event.find params[:id]
@event.increment! :votes
respond_with @event
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.