Created
February 1, 2015 06:52
-
-
Save ryankbales/500518d17faf58fd197e to your computer and use it in GitHub Desktop.
Voting of Comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#routes | |
PostitTemplate::Application.routes.draw do | |
root to: 'posts#index' | |
get 'register', to: 'users#new' | |
get '/login', to: 'sessions#new' | |
post '/login', to: 'sessions#create' | |
get '/logout', to: 'sessions#destroy' | |
resources :posts, except: [:destroy] do | |
member do | |
post :vote | |
end | |
resources :comments, only: [:create] do | |
member do | |
post :vote | |
end | |
end | |
end | |
resources :categories, only: [:index, :new, :create, :show] | |
resources :users, only: [:show, :create, :edit, :update] | |
end | |
#vote model | |
class Vote < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :voteable, polymorphic: true | |
validates_uniqueness_of :user, scope: :voteable | |
end | |
#comment model | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
belongs_to :user, foreign_key: :user_id | |
has_many :votes, as: :voteable | |
validates :body, presence: true | |
def total_votes | |
up_votes - down_votes | |
end | |
def up_votes | |
self.votes.where(vote: true).size | |
end | |
def down_votes | |
self.votes.where(vote: false).size | |
end | |
end | |
#comments controller | |
class CommentsController < ApplicationController | |
before_action :require_user | |
def create | |
@post = Post.find(params[:post_id]) | |
@comment = @post.comments.build(params.require(:comment).permit(:body)) | |
@comment.user = current_user | |
if @comment.save | |
flash[:notice] = "Your comment was added." | |
redirect_to post_path(@post) | |
else | |
render 'posts/show' | |
end | |
end | |
def vote | |
comment = Comment.find(params[:id]) | |
@vote = Vote.create(voteable: comment, user: current_user, vote: params[:vote]) | |
if @vote.valid? | |
flash[:notice] = "Your vote was counted." | |
else | |
flash[:error] = "Didn't you already vote on this comment?" | |
end | |
redirect_to :back | |
end | |
end | |
#voting view code from _comments.html.erb | |
<div class='col-md-1 well text-center'> | |
<%= link_to vote_post_comment_path(comment.post, comment, vote: true), method: 'post' do %> | |
<span class='glyphicon glyphicon-arrow-up'></span> | |
<% end %> | |
<br> | |
<%= comment.total_votes %> votes | |
<br> | |
<%= link_to vote_post_comment_path(comment.post, comment, vote: false), method: 'post' do %> | |
<span class='glyphicon glyphicon-arrow-down'></span> | |
<% end %> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment