I am using the acts as votable gem on my rails 4 app.
I have finally gotten it to work using ajax, so the page does not refresh when a user votes, however, the vote.size doesn't update until the page is refreshed.
Here is my controller action:
def upvote
@article = Article.find(params[:article_id])
@subarticle = @article.subarticles.find(params[:id])
session[:voting_id] = request.remote_ip
voter = Session.find_or_create_by(ip: session[:voting_id])
voter.likes @subarticle
respond_to do |format|
format.html {redirect_to :back }
format.json { render json: { count: @subarticle.get_upvotes.size } }
end
end
and view:
<%= link_to like_article_subarticle_path(@article, subarticle), class: "vote", method: :put, remote: true, data: { type: :json } do %>
<button type="button" class="btn btn-success btn-lg" aria-label="Left Align" style="margin-right:5px">
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Helpful
</button><span class="badge" style="margin-right:10px"><%= subarticle.get_upvotes.size %></span>
<% end %>
<script>
$('.vote')
.on('ajax:send', function () { $(this).addClass('loading'); })
.on('ajax:complete', function () { $(this).removeClass('loading'); })
.on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); })
.on('ajax:success', function(e, data, status, xhr) { $(this).html("Thank you for voting!"); });
</script>
As of now, when a user votes, it completely get's rid of the "helpful" button and upvote size, and displays the html"Thank you for voting".
I am having trouble figuring out how to keep the button and simply update the upvote.size to the correct number. I have tried assigning a class to the upvote size and then using something like this: $('.item-class').html(data.count)
but no luck.
Any recommendations? Thank you!