2016-11-27 50 views
1

在我的应用程序中,我有可投票通过AJAX进行投票,但AJAX工作正常,但我想通过AJAX投票更新帖子的状态(无论是同意的里程碑)以及。状态部分:如何通过Rails应用程序中的AJAX更新if语句通过AJAX

_milestone.html.erb

<% if post.agreed? %> Agreed Milestone <% elsif post.milestone? %> 
Proposed Milestone <% end %> 

posts_controller.rb

def upvote 
    @post = Post.find(params[:post_id]) 
    respond_to do |format| 
    format.html { redirect_to @post } 
    format.js 
    @post.upvote_by current_user 
    end 
    if @post.votes_for.up.size == count_users 
     @post.toggle! :agreed 
    end 
end 

upvote.js.erb

$('#voting-<%= @post.id %>').hide(); 
$('#agreed-<%= @post.id %>').html("<%= j render(partial: 'posts/agreed', 
locals: {post: @post}) %>"); 
$('#milestone-<%= @post.id %>').html("<%= j render(partial: 'posts/milestone', 
locals: {post: @post}) %>"); 

同意部分是选民名单。

因此,当发布达到一定数量的选票时,它的布尔值同意为true。我想要在视图中更新状态。我尝试渲染里程碑元素作为部分和其他几种方法,但是if语句永远不会执行并且状态不会更新。

+0

您应该将upvote.js.erb添加到您的问题中,以便我们更清楚地了解如何更新视图。 – David

回答

1

你可能需要渲染视图之前更新它,

def upvote 
    @post = Post.find(params[:post_id]) 
    @post.upvote_by current_user 
    if @post.votes_for.up.size == count_users 
     @post.toggle! :agreed 
    end 
    respond_to do |format| 
    format.html { redirect_to @post } 
    format.js 
    end 
end 

希望帮助!

+0

非常有帮助。谢谢。按照您的建议,我将里程碑作为部分和修改控制器导出。我将最后一行添加到了我的upvote.js,erb。 – bosp