Skip to content

Instantly share code, notes, and snippets.

@jeremyf
Last active December 17, 2015 16:09
Show Gist options
  • Save jeremyf/5636323 to your computer and use it in GitHub Desktop.
Save jeremyf/5636323 to your computer and use it in GitHub Desktop.
Follow-up to Extra Credit Challenge for Chicago 2013 RailsBridge for Code4Lib-ers
<!-- Found in /app/views/topics/index.html.erb -->
<h1>Listing topics</h1>
<table>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<% @topics.each do |topic| %>
<tr>
<td><%= link_to topic.title, topic %></td>
<!-- replaced topic.votes.length with topics.votes_count -->
<td><%= pluralize(topic.votes_count, "vote") %></td>
<td><%= button_to '+1', votes_path(topic_id: topic.id), method: :post %></td>
<td><%= link_to 'Delete', topic, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Topic', new_topic_path %>
# Found in ./app/models/topic.rb
class Topic < ActiveRecord::Base
attr_accessible :title, :body
has_many :votes
def self.sorted
# There are ways to do this with database agnostic syntax, but the resulting
# Ruby/Rails code is rather overwhelming
find_by_sql(
"SELECT topics.*,
(SELECT count(votes.topic_id) FROM votes WHERE votes.topic_id = topics.id)
AS votes_count
FROM topics
ORDER BY votes_count"
)
end
def votes_count
# In the above SQL there is the line that counts the votes and creates the
# selected query column "votes_count", which means that each Topic has a
# "votes_count" attribute.
#
# If we have the attribute, use it, otherwise compute the attribute. For
# this to truly be effective, in the index page, replace "topic.votes.count"
# with "topic.vote_count"
attributes['votes_count'] || votes.count
end
end
# Found in ./app/controllers/topics_controller.rb
class TopicsController < ApplicationController
# GET /topics
# GET /topics.json
def index
# @topics = Topic.all
@topics = Topic.sorted
respond_to do |format|
format.html # index.html.erb
format.json { render json: @topics }
end
end
# ... Removed for brevity ...
end
# Found in ./app/models/vote.rb
class Votes < ActiveRecord::Base
attr_accessible :topic_id
belongs_to :topic
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment