N個ActiveRecordのオブジェクト(モデルA)があったとして、それらが持つassociation(モデルB)のデータは要らずcountだけ表示したいとする。 その際、以下のような4つの手が思いつく。 AのテーブルにBの数をキャッシュするカラムを追加し、それをSELECTする belongs_toのcounter_cacheオプション N回BのCOUNTクエリを走らせる 普通にやるとこうなる LEFT JOINとGROUP BY A.idでB.idをCOUNTする がんばってクエリを1回にするとこうなる N個のA.idからB.a_idをpluckしてきて各idごとの個数をとる これをやる方法がないので作った: k0kubun/activerecord-has_count count専用のhas_count associationを生やし、外部キーをpluckする専用のpreloade