如何在Rails 3中加入表并计算记录? [英] How to join a table and count records in Rails 3?

查看:32
本文介绍了如何在Rails 3中加入表并计算记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Collection 类,里面有很多硬币.我正在尝试选择包含两个以上硬币的收藏.目前,我通过直接的 Ruby 做到这一点没有问题,但效率极低.

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.

我当前的代码:

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

我如何通过与 Arel 的 joins 调用来实现这一点?

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

谢谢!

推荐答案

回答我自己的问题:

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

KJF 的帽子提示,他们询问了 这个类似的问题krakover 回答它.

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

这篇关于如何在Rails 3中加入表并计算记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆