少於 1 分鐘閱讀

推薦 gem

acts_as_votable

使用方式

  1. 加入acts_as_votable

     # [path] gemfile
     gem 'acts_as_votable', '~> 0.10.0'
    
     bundle install
    

    (記得要重開server)

  2. 在想要施作的model中加入 acts_as_votable

  3. route.rb加入喜歡/不喜歡連結

     # [path] route.rb
     resources :links do
       member do
         get 'upvote' 
         get 'downvote'
       end
     end
    
  4. 在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
    
  5. 在畫面上加上這兩顆按鈕即可

     <% link_to 'Upvote', upvote_link_path(link) %>
     <% link_to 'Upvote', downvote_link_path(link) %>
    
  6. 計算數量時

     @post.votes_for.size    # => 5 # 總數
     @post.get_likes.size    # => 3 # 喜歡
     @post.get_dislikes.size # => 2 # 不喜歡
    

留言