2
2

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 1 year has passed since last update.

Railsで子モデルの所有数ランキングを取得するスコープの書き方

Last updated at Posted at 2021-11-16

個人開発で必要になったのですが、どこにも書いておらず調べるのが大変だったので残しておきます。

app/model/parent.rb
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
  scope :how_many_children, -> { joins(:children).group("parent.name").order(count_all: :desc).limit(3).count }
  # => {"親名"=>子テーブル所有数(一位), "親名"=>子テーブル所有数(二位), "親名"=>子テーブル所有数(三位)}
end

今思えばこれ(Railsガイド)の応用だったので、そこまで我流のやり方ではないと思います。

自分の場合はBEST3で十分だったのですが、limitをつけなければ親全員のデータを取得できます。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?