1

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.

1
  • You should add the upvote.js.erb to your question so we have a clearer idea of how you are updating your view. Commented Nov 27, 2016 at 11:51

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Great it helped. Thank you. I exported milestone as partial and modified controller as you suggested. I added last line to my upvote.js,erb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.