#Acts As Votable (aka Acts As Likeable)
Acts As Votable is a Ruby Gem specifically written for Rails/ActiveRecord models. The main goals of this gem are:
- Allow any model to be voted on, like/dislike, upvote/downvote, etc.
- Allow any model to be voted under arbitrary scopes.
- Allow any model to vote. In other words, votes do not have to come from a user, they can come from any model (such as a Group or Team).
- Provide an easy to write/read syntax.
##Steps
###Step 1
Install gem:
install: gem 'acts_as_votable', '~> 0.10.0'
###Step 2
Run bundle install
###Step 3
Acts As Votable uses a votes table to store all voting information. To generate and run the migration just use:
rails generate acts_as_votable:migration
rake db:migrate
Schema:
create_table "votes", force: :cascade do |t|
t.integer "votable_id"
t.string "votable_type"
t.integer "voter_id"
t.string "voter_type"
t.boolean "vote_flag"
t.string "vote_scope"
t.integer "vote_weight"
t.datetime "created_at"
t.datetime "updated_at"
end
###Step 4
Add: acts_as_votable
in the model file
class Post < ActiveRecord::Base
acts_as_votable
end
###Step 5
Add route to the like method:
post "cities/:id/posts/:id/like", to:"posts#like"
###Step 6
Add Like button to the HTML page:
<div><%= button_to "Like", action: :like%></div><br>
<div><%= @post.votes_for.size %> Likes</div>
Add like method in the post controller:
def like
@post = Post.find(params[:id])
@post.liked_by current_user
@likes = @post.votes_for.size
#call the show method to re-render the page
show
end
##Additional notes:
- One user gets one vote
- If you prefer to have no page refresh, implement ajax to call the like method
- Refer to the github documentation below for fulll list of methods
##Resources