bosp bosp - 7 days ago 6
Ajax Question

How to update if statement in views through AJAX in Rails app

In my app I have votable posts where you vote through AJAX which works fine but I want to update status of the post (whether it is agreed milestone) upon voting through AJAX as well. Status partial:

_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}) %>");


Agreed partial is list of voters.

So when post reaches certain number of votes it changes its boolean agreed to true. I want to then update status in views. I tried rendering milestone element as partial and several other approaches but the if statement is never executed and status does not update.

RSB RSB
Answer

You probably need to update it before rendering the view,

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

Hope that helps!

Comments