Skip to content

Instantly share code, notes, and snippets.

@timriley
Forked from joho/some_view.html.erb
Created March 24, 2011 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriley/884359 to your computer and use it in GitHub Desktop.
Save timriley/884359 to your computer and use it in GitHub Desktop.
<ul>
<% User.all.with_item_counts do |user| %>
<li><%= user.username %> - Items: <%= user.calculated_item_count %>
<% end %>
</ul>
class User < ActiveRecord::Base
has_many :items
# screw n+1 problems from loading users, then fetching each user's item count
# screw memory bloat from User.all.include(:items) and then user.items.size or count
# screw custom sql, it's annoying to write, and you can't chain it
# let arel + the db do the work!
def with_item_counts
column_names = columns.collect(&:name)
select(column_names + ['count(items.id) as calculated_item_count']).joins('items').group(column_names)
end
def calculated_item_count
super or raise 'use #with_item_counts scope if you want item counts'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment