Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Acts As Votable

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 687
    Comment on it

    Acts As Votable is a Ruby Gem. It is used to give user a way to Like and unlike something(Post, Link etc) and update the counter each time they click without refreshing the page.
    This gem is specically written for Rails/ActiveRecord models, and allow a model to be voted (like,dislike etc).

    Lets install the gem by the command below:
     

    gem 'acts_as_votable'

    Acts As Votable uses a votes table to store all voting information. To generate and run the migration just run the below commands.

    rails generate acts_as_votable:migration
    rake db:migrate

    Now we need to add acts_as_votable helper to our model(app/models/link.rb).

    class Link < ActiveRecord::Base
      acts_as_votable
    end


    Next we will set up the views to interact with our new functionality. So we need some routes. In app/config/routes.rb, we'll need to add another block to our links section.

    resources :links do
      member do
        put "like", to: "links#liked_by_user"
        put "dislike", to: "links#disliked_by_user"
      end
    end

    This block invokes liked_by_user and disliked_by_user methods in the links controller. So open app/controllers/links_controller.rb file and add the below code.

    def liked_by_user
      @link = Link.find(params[:id])
      @link.upvote_by current_user
      redirect_to :back
    end  
    
    def disliked_by_user
      @link = Link.find(params[:id])
      @link.downvote_by current_user
      redirect_to :back
    end

    Finally we will create links in our view to like and dislike.
     

    <%= link_to like_link_path(link), method: :put do %>
      Like
      <%= link.get_upvotes.size %>
    <% end %>
    
    <%= link_to dislike_link_path(link), method: :put do %>
      Dislike
      <%= link.get_downvotes.size %>
    <% end %>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: