开发者

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

开发者 https://www.devze.com 2023-03-27 12:25 出处:网络
I have a Collection class which has many coins. I am trying to select collections which have more than two coins.

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?开发者_JAVA技巧

Thanks!


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.


Add counter_cache columns and query them.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号