Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join a table and count records in Rails 3?

I have a Collection class which has many coins. I am trying to select collections which have more than two coins. Currently, I have no problem doing that through straight Ruby, but that's extremely inefficient.

My current code:

collections = Collection.all.select { |c| c.coins.count > 2 }

How do I achieve that through a joins call with Arel?

Thanks!

like image 925
Yuval Karmi Avatar asked Aug 09 '11 23:08

Yuval Karmi


2 Answers

To answer my own question:

Collection.joins(:coins).group("coins.collection_id").having("count(coins.id) > 2")

Hat tip to KJF who asked this similar question and to krakover for answering it.

like image 148
Yuval Karmi Avatar answered Sep 20 '22 03:09

Yuval Karmi


Add counter_cache columns and query them.

http://railscasts.com/episodes/23-counter-cache-column

like image 26
BvuRVKyUVlViVIc7 Avatar answered Sep 21 '22 03:09

BvuRVKyUVlViVIc7