-
-
Save timriley/884359 to your computer and use it in GitHub Desktop.
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
<ul> | |
<% User.all.with_item_counts do |user| %> | |
<li><%= user.username %> - Items: <%= user.calculated_item_count %> | |
<% end %> | |
</ul> |
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
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