简体   繁体   English

在Rails 4中可以取消投票的Upvote按钮

[英]Upvote button that can be unupvoted in Rails 4

I am creating a Rails 4 app in which a user can upvote a given post through the acts_as_votable gem. 我正在创建一个Rails 4应用程序,用户可以在其中通过act_as_votable gem投票给定帖子。 Let's say as a user I press the upvote button, how would I make it so that if I press the SAME button again, the vote gets taken away, so in essence an "unupvote"? 假设作为用户我按下了upvote按钮,我将如何做到这一点,如果再次按下SAME按钮,投票将被取消,因此实质上是“ unupvote”?

Here is what my upvote method looks like in my posts controller: 这是我的posts控制器中upvote方法的外观:

def upvote
  @post = Post.find(params[:id])
  @post.upvote_by current_user
  redirect_to :back
end

My post model 我的帖子模型

class Post < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
end

And finally this how I am rendering the button in my views 最后,这就是我在视图中渲染按钮的方式

<div class="btn-group">
  <%= link_to like_post_path(post), method: :put, class: "btn btn-default btn-sm" do %>
    <span class="glyphicon glyphicon-chevron-up"></span>
    Upvote
    <%= post.get_upvotes.size %>
  <% end %>
</div>

Thanks for the help guys! 感谢您的帮助!

acts_as_votable has an unvote_up method you can use. acts_as_votableunvote_up您可以使用方法。 I'd do something like this (assuming your like_post_path references the upvote action): 我会做这样的事情(假设您的like_post_path引用了upvote操作):

def upvote
  @post = Post.find(params[:id])

  if current_user.up_votes @post 
    @post.unvote_up current_user
  else
    @post.upvote_by current_user
  end

  @post.create_activity :upvote, owner: current_user
  redirect_to :back
end

You'll also need to add acts_as_voter to your User model so you can get the up_votes helper: 您还需要添加acts_as_voter到您的用户模型,这样你就可以得到up_votes帮手:

class User < ActiveRecord::Base
  acts_as_voter
end

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

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