Javascript投票acts_as_votable

时间:2014-04-06 23:49:18

标签: javascript ruby-on-rails

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

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

这是我以前的(有效):

在我的评论控制器中:

  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 %>

这就是我现在所拥有的:

在我的评论控制器中:

 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?

1 个答案:

答案 0 :(得分:4)

您的日志说请求格式为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 } %> 

这将告诉控制器您想要JSON响应而不是Javascript响应。

修改 - 评论中的更新。

更新要使用的控制器,

format.json { render json: { count: @comment.likes.size } }

更新要使用的JS,

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