我有一个 rails 应用程序,其中我的 Posts 模型有评论并且评论是可投票的。我正在使用acts_as_votable。

我目前对评论工作进行投票。现在我正在尝试实现一些 javascript,以便每次有人对评论进行投票时都不必刷新页面,以便投票通过。

这是我之前的(正在工作):

在我的评论 Controller 中:

  def upvote_post_comment
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.liked_by current_user

  respond_to do |format|
    format.html {redirect_to :back}
  end
end

在我看来:
<% if user_signed_in? && current_user != comment.user && !(current_user.voted_for? comment) %>


<%= link_to image_tag(‘vote.png'), like_post_comment_path(@post, comment), method: :put %> <a>
<%= "#{comment.votes.size}"%></a>


<% elsif user_signed_in? && (current_user = comment.user) %>

<%= image_tag(‘voted.png')%><a><%= "#{comment.votes.size}"%></a>

<% else %>

<%= image_tag(‘voted.png')%><a><%= "#{comment.votes.size}"%></a>
<% end %>

这就是我现在所拥有的:

在我的评论 Controller 中:
 def upvote_post_comment
 @post = Post.find(params[:post_id])
 @comment = @post.comments.find(params[:id])
 @comment.liked_by current_user

respond_to do |format|
format.html {redirect_to :back }
format.json { render json: { count: @comment.liked_count } }
end
end

在我看来:
<% if user_signed_in? && current_user != comment.user && !(current_user.voted_for? comment) %>


    <%= link_to image_tag(‘vote.png'), like_post_comment_path(@post, comment), method: :put, class: 'vote', remote: true %>
<a><%= "#{comment.votes.size}"%></a>


  <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 (data) { $(this).html(data.count); });

    </script>


  <% elsif user_signed_in? && (current_user = comment.user) %>

  <%= image_tag(‘voted.png')%><a><%= "#{comment.votes.size}"%></a>


  <% else %>

  <%= image_tag(‘voted.png')%><a><%= "#{comment.votes.size}"%></a>


    <% end %>

这向我显示了错误消息:“出现问题”

当我刷新页面时,我看到投票通过了,我在终端中看到了这一点:
Started PUT “/1/comments/1/like" for 127.0.0.1 at 2014-04-06 18:54:38 -0400
Processing by CommentsController#upvote_post_comment as JS
  Parameters: {"post_id"=>”1”, "id"=>”1”}

如何通过 Javascript 进行投票?为了让投票通过,投票计数更新,投票图标更新到voted.png而不是vote.png?

最佳答案

您的日志显示请求的格式为 JS。

Processing by CommentsController#upvote_post_comment as JS

data: { type: :json } 添加到 link_to 方法以请求这样的 JSON 格式,
<%= link_to image_tag('vote.png'), like_post_comment_path(@post, comment), method: :put, class: 'vote', remote: true, data: { type: :json } %>

这将告诉 Controller 您需要 JSON 响应而不是 Javascript 响应。

编辑 - 来自评论的更新。

更新 Controller 以使用,
format.json { render json: { count: @comment.likes.size } }

更新JS使用,
.on('ajax:success', function(e, data, status, xhr) { $(this).html(data.count); });

关于Javascript投票acts_as_votable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22901455/

10-12 07:22
查看更多