[Rails] 實作按讚(喜歡/不喜歡)功能
推薦 gem
使用方式
-
加入acts_as_votable
# [path] gemfile gem 'acts_as_votable', '~> 0.10.0'
bundle install
(記得要重開server)
-
在想要施作的model中加入
acts_as_votable
-
route.rb加入喜歡/不喜歡連結
# [path] route.rb resources :links do member do get 'upvote' get 'downvote' end end
-
在links_controller加入
def upvote @link = Link.find(params[:id]) @link.liked_by(current_user) redirect_to :back end def downvote @link = Link.find(params[:id]) @link.disliked_by(current_user) redirect_to :back end
-
在畫面上加上這兩顆按鈕即可
<% link_to 'Upvote', upvote_link_path(link) %> <% link_to 'Upvote', downvote_link_path(link) %>
-
計算數量時
@post.votes_for.size # => 5 # 總數 @post.get_likes.size # => 3 # 喜歡 @post.get_dislikes.size # => 2 # 不喜歡
留言