【发布时间】:2015-07-07 05:36:35
【问题描述】:
我在我的 rails 4 应用程序中使用这些行为作为可投票的宝石。
我终于使用 ajax 让它工作了,所以当用户投票时页面不会刷新,但是,vote.size 在页面刷新之前不会更新。
这是我的控制器操作:
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
并查看:
<%= 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>
截至目前,当用户投票时,它完全摆脱了“帮助”按钮和点赞大小,并显示html“感谢您的投票”。
我无法弄清楚如何保留按钮并将 upvote.size 更新为正确的数字。我曾尝试为 upvote 大小分配一个类,然后使用如下内容:$('.item-class').html(data.count) 但没有运气。
有什么建议吗?谢谢!
【问题讨论】:
-
您是否检查了 javascript 控制台以确保没有 javascript 错误?
-
我收到了
Failed to load resource: the server responded with a status of 404 (Not Found),但我认为这与@TarynEast 的投票系统无关 -
单击“网络”选项卡并单击标记为红色的行...它可能会为您提供有关实际错误的更多详细信息(同时检查您的 Rails 日志)。
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4