我有一个有事件的小应用程序。在事件索引 View 中,我迭代所有事件并显示一些数据。在each
里面我有一个指向“Upvote”特定事件的链接,这是一个ajax请求。由于某些原因,我的 View 不会立即更新,而是在我再次单击“投票”时更新。
这是我的“点赞”链接
<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
值(value)。
<span style="font-family:MetaSerifOT-Book;font-size:13px;">
<%= pluralize(event.votes, "vote") %>
</span>
问题是当我点击“Upvote”链接时,我的请求得到通过,votes
我的事件模型中的字段已更新,但 View 不会更新,直到我单击 Upvote
再次。我不确定发生了什么事。有什么想法或建议吗?
更新
这是我设置id的地方:upvotes_<%= event.id %>
我已经隔离了Votes
在部分内计数。
<div id="upvotes_<%= event.id%>">
<%= render 'upvote', event: event %>
</div>
最佳答案
问题出在 Controller 代码中。我认为 @event 对象没有被重新加载。一种解决方案是您必须在 View 中重新加载 @event 对象,例如
$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event.reload )%>");
.
关于javascript - Rails link_to 与 ajax 远程 true 不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941052/