简体   繁体   中英

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. 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"?

Here is what my upvote method looks like in my posts controller:

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. I'd do something like this (assuming your like_post_path references the upvote action):

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:

class User < ActiveRecord::Base
  acts_as_voter
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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