Reputation: 1367
I know I've seen this before but I can't find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part down:
@line_items = @project.line_items.all(:group => "device_id")
This is for my line item index view, which is just a table displaying the line items. How do I make a column in that table for "count" now that the line items are grouped by device?
Upvotes: 87
Views: 90719
Reputation: 7733
hash of devise_id as key and associated records count
@project.line_items.group(:device_id).count
Upvotes: 24
Reputation: 1041
I think you can try this as well.
@project.line_items.group(:device_id).pluck("device_id, count(device_id)")
^^ This gives array of arrays with elements 'device_id and count'
Upvotes: 14
Reputation: 61
For only count pluck would be faster here rather than group
@project.line_items.pluck(:device_id).count
@project.line_items.pluck(:device_id).uniq.count
Upvotes: 1
Reputation: 17577
You can do count
on line_items
which will return you an ordered hash of device_id
and count
.
@project.line_items.group(:device_id).count
Upvotes: 163
Reputation: 2808
After this commit:
https://github.com/rails/rails/commit/a1c05dd8b9bd3623289d3aa73dda2943d620cc34
there's a new way to do the same thing:
@project.line_items.count(:group => LineItem.arel_table[:device_id])
Upvotes: 1
Reputation: 66711
something like
User.all(:joins => :comments, :select => "users.*, count(comments.id) as comments_count", :group => "users.id")
might also work...
Upvotes: 5
Reputation: 29442
Just add a :select
option:
@line_items = @project.line_items.all(
:group => "device_id",
:select => "device_id, COUNT(*) as count"
)
Then each @line_item
will have a count
attribute.
Upvotes: 10