has_manyなテーブルの要素がゼロの場合どうしたら良いかと思い
調べてみらたいい感じのやつが見つかりました

SQL書こうかと思いましたが、active recordの機能を使えたので、
コードきれいに保つことができましたと。

class Model < ApplicationRecord
  has_many :model_children
  scope :without_children, -> { left_outer_joins(:model_children).where(model_children: { id: nil }) }

dnd

class ModelChild < ApplicationRecord
  belongs_to :model
dnd

参考記事

Select all rows that have no children
Rails 4 scope to find parents with no children

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA