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

[亡魂溺海] 提交于 2019-12-20 19:16:12

问题


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!


回答1:


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.




回答2:


Add counter_cache columns and query them.

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



来源:https://stackoverflow.com/questions/7004048/how-to-join-a-table-and-count-records-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!