[英]Rails link_to with ajax remote true not updating view
I have this little app that has events. 我有一个有事件的小应用程序。 In my index view for events I iterate through all events and display some data. 在事件的索引视图中,我遍历所有事件并显示一些数据。 In inside the each
loop I have a link to 'Upvote' a particular event, this is an ajax request. 在each
循环中,我都有一个指向“ Upvote”特定事件的链接,这是一个ajax请求。 For some reasons my view wont update right away but update when I clicked 'Upvote' again. 由于某些原因,我的视图不会立即更新,但是当我再次单击“ Upvote”时会更新。
Here is my link to 'Upvote' 这是我指向“ Upvote”的链接
<div id="upvote_link_<%= event.id%>">
<%= link_to('Upvote', upvote_event_path(event), method: :post, remote: true)%>
</div>
This is my upvote
method where I increment the votes
field. 这是我upvote
,我递增法votes
现场。
def upvote
@event = Event.find(params[:id])
Event.increment_counter(:votes, @event.id)
respond_to do |format|
format.js
end
end
Next is my upvote.js.erb
where I replaced the old votes
value with the new value. 接下来是我的upvote.js.erb
,在其中我用新值替换了旧的votes
值。
$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event )%>");
Next is my _upvote.html.erb
partial that replaces the old votes
value. 接下来是我的_upvote.html.erb
部分,它替换了旧的votes
值。
<span style="font-family:MetaSerifOT-Book;font-size:13px;">
<%= pluralize(event.votes, "vote") %>
</span>
The problem is when I clicked the 'Upvote' link my request goes through and the votes
field in my Event model gets updated but the view wont update until I clicked Upvote
again. 问题是,当我单击“ Upvote”链接时,我的请求通过了,事件模型中的“ votes
字段得到了更新,但是视图一直没有更新,直到我再次单击“ Upvote
。 I am not sure what is going on. 我不确定发生了什么。 Any ideas or suggestions? 有什么想法或建议吗?
Update This is where I set up the id: upvotes_<%= event.id %>
I have isolated the Votes
count inside a partial. 更新这是我设置ID的地方: upvotes_<%= event.id %>
我已将部分中的Votes
数隔离了。
<div id="upvotes_<%= event.id%>">
<%= render 'upvote', event: event %>
</div>
The problem is in controller code. 问题出在控制器代码中。 The @event object is not getting reloaded, I think. 我认为@event对象没有被重新加载。 One solution is you have to reload the @event object either in the view like 一种解决方案是您必须在类似这样的视图中重新加载@event对象
$('#upvotes_<%= @event.id %>').html("<%= escape_javascript (render 'upvote', event: @event.reload )%>");
. 。
To add to Santanu
's answer, you'll want to look at your method's code: 要添加到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.