adds votes to debates [#9]

This commit is contained in:
rgarcia
2015-07-18 18:10:19 +02:00
parent b8e41551f9
commit e006549092
5 changed files with 69 additions and 4 deletions

View File

@@ -0,0 +1,20 @@
class VotesController < ApplicationController
before_action :set_debate
before_action :authenticate_user!
def create
register_vote
notice = @debate.vote_registered? ? "Gracias por votar." : "Tu voto ya ha sido registrado."
redirect_to @debate, notice: notice
end
private
def set_debate
@debate = Debate.find(params[:debate_id])
end
def register_vote
@debate.vote_by voter: current_user, vote: params[:value]
end
end

View File

@@ -1,6 +1,27 @@
require 'numeric'
class Debate < ActiveRecord::Base
acts_as_votable
validates :title, presence: true
validates :description, presence: true
validates :terms_of_service, acceptance: { allow_nil: false }, on: :create
#vote can be 'likes' or 'dislikes'
def percentage(vote)
return if total_votes == 0
send(vote).percent_of(total_votes)
end
def likes
get_likes.size
end
def dislikes
get_dislikes.size
end
def total_votes
votes_for.size
end
end

View File

@@ -4,5 +4,22 @@
<p>Creado el: <%= l @debate.created_at.to_date %></p>
</div>
<div>
<div id='in_favor'>
<%= link_to "up", debate_votes_path(@debate, value: 'yes'), method: "post" %>
<%= @debate.percentage('likes') %>%
</div>
<div id='against'>
<%= link_to "down", debate_votes_path(@debate, value: 'no'), method: "post" %>
<%= @debate.percentage('dislikes') %>%
</div>
Votos <%= @debate.total_votes %>
</div>
<br/><br/>
<div>
<%= link_to 'Edit', edit_debate_path(@debate) %> |
<%= link_to 'Back', debates_path %>
</div>

View File

@@ -5,7 +5,9 @@ Rails.application.routes.draw do
# You can have the root of your site routed with "root"
root 'welcome#index'
resources :debates
resources :debates do
resources :votes, only: :create
end
# Example of regular route:
# get 'products/:id' => 'catalog#view'

5
lib/numeric.rb Normal file
View File

@@ -0,0 +1,5 @@
class Numeric
def percent_of(n)
(self.to_f / n * 100).to_i
end
end