prognar
prognar

Reputation: 57

Counting a collection of models in rails

Currently I have 3 models: User, Collection and Item.

A User has many Items through Collections
An Item has many Users through Collections

To get a User's collection, I can do user.items and display them accordingly.

What I would like to be able to do is aggregate the duplicate items for this list.

Say a User adds Item 1, then Item 2 and then another Item 1.
The list should be:

User

-Item 1 Name - Item 1 Description - Item 1 Category - Qty 2
-Item 2 Name - Item 2 Description - Item 2 Category - Qty 1

Upvotes: 0

Views: 202

Answers (2)

Jim Stewart
Jim Stewart

Reputation: 17323

Check out Enumerable#group_by

You can group all the items with something like this:

user.items.group_by(&:id)

...which will get you a hash where the key is an item id and the value is an array of items sharing that id. You can then further collapse the individual items down to just a count:

Hash[user.items.group_by(&:id).map {|k,v| [k, v.size]}]

...which will get you a hash where the key is the item id and the value is the number of items with that id.

Upvotes: 1

Fiona T
Fiona T

Reputation: 1929

In your controller:

item_groups = user.items.group_by(&:id)
@item_counts = item_groups.map {|item_id,items| [items.first, items.size]}

In your view:

@item_counts.each do |item, size|
  ... item.name, size or whatever you want to print

Upvotes: 0

Related Questions