Acts As Votable Ajax Vote Size Not Updating Rails

喜夏-厌秋 提交于 2020-04-19 18:14:41

问题


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!


回答1:


$('.item-class').html(data.count)

item-class doesn't seem to be declared in your template anywhere... but even if it did, if you call it like this, it will likely match more than one thing on the page, so this replace won't work.

The reason why the button is being replaced is you are replacing the html of "this" (which is defined as the whole section marked with the class .vote)

If you want to replace just the item-class within the .vote section (ie leave the button intact) then you need to a) add something with the class of 'item-class' and b) reduce what you are replacing to that. eg:

$(this).first('.item-class').html("Thank you for voting!");

(note I've not bug-tested this - you may need to google javascript first to make sure this is the correct usage).



来源:https://stackoverflow.com/questions/31260506/acts-as-votable-ajax-vote-size-not-updating-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!