繁体   English   中英

Javascript投票acts_as_votable

[英]Javascript voting acts_as_votable

我有一个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?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM