Skip to content

Instantly share code, notes, and snippets.

@sirramongabriel
Created October 19, 2012 16:32
Show Gist options
  • Save sirramongabriel/3919201 to your computer and use it in GitHub Desktop.
Save sirramongabriel/3919201 to your computer and use it in GitHub Desktop.
Vote counter code...
# post_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.find(:all)
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html do
redirect_to root_path, success: "Post saved successfully"
end
else
format.html { render action: 'index' }
end
end
end
def show
# Post
@post = Post.find(params[:id])
# Comments assiciated by :post_id
@comments = @post.comments.all
@comment = @post.comments.build(params[:comment])
@comment.save
end
def edit
end
end
# votes_controller
class VotesController < ApplicationController
def create
# Vote.create(post_id: params[:post_id], vote: params[:vote])
@post = Post.find(params[:post_id])
@post.votes.create(vote: params[:vote])
respond_to do |format|
format.html do
redirect_to posts_path, success: "HTML says your vote was counted!"
end
format.js do
end
end
end
end
# post.rb
class Post < ActiveRecord::Base
attr_accessible :URL, :description, :is_link
has_many :comments, dependent: :destroy
has_many :votes, dependent: :destroy
def vote_total
votes.where(vote: true).size - votes.where(vote: false).size
# votes.increment_counter(:vote, :post_id)
end
end
# vote.rb
class Vote < ActiveRecord::Base
attr_accessible :vote, :post_id
belongs_to :post, dependent: :destroy
end
# posts/index.html.erb
<h5>Posts#index</h5>
<small><i>Find me in app/views/posts/index.html.erb</i></small>
<hr />
<div class="hero hero-unit">
<button><%= link_to "Create a post", new_post_path %></button>
<hr />
<ul class="unstyled">
<% @posts.each do |post| %>
<h5><small>post ID: </small><%= post.id %></h5>
<li><%= post.URL %></li>
<li>
<%= link_to post.description, post %>
</li>
<li>
<ul class="unstyled">
<li><small><i>submitted <%= time_ago_in_words(post.created_at) %> ago.</i></small></li>
</ul>
</li>
<li>
<%= pluralize(post.comments.count, 'comment') %>
</li>
<li>
<button class="btn btn-mini btn-success">
<%= link_to '', post_votes_path(post, vote: true), method: :post, remote: true, class: 'icon-arrow-up' %>
</button>
<button class="btn btn-mini btn-danger">
<%= link_to '', post_votes_path(post, vote: false), method: :post, remote: true, class: 'icon-arrow-down' %>
</button>
<span id="post_<%= post.id %>_votes"><%= post.vote_total.to_s + " votes" %></span>
</li>
<% end %>
<hr />
</ul>
</div><!-- END hero, hero-unit CLASS -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment