39
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecordでcount(*)の結果をsortして上位をリストアップ。

Last updated at Posted at 2013-04-08

特定の条件を満たすコードを
書き方分からなかったのでメモ。joinも行っていたのでややこしかった。

Foge.joins(:foo_bar).group('foo_bar.name')
                    .order('count_foo_bars_name desc')
                    .limit(10)
                    .count('foo_bar.name')

記述の順番が直感的ではないので注意。count_foo_bars_nameの部分は一度ActiveRecordが吐き出してるSQL文を見て COUNT(*) AS <この部分> を抜き出してくると良い。
結果作られるSQL文はこんな感じ

SELECT COUNT(foo_bar.name) AS count_foo_bars_name,
       foo_bars.name AS foo_bars_name
    FROM "Foges"
    INNER JOIN "foo_bars" ON "foo_bars"."id" = "foges"."foo_bar_id"
    GROUP BY foo_bars.name
    ORDER BY count_foo_bars_name desc
    LIMIT 10;
39
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?