has_manyなテーブルの要素がゼロの場合どうしたら良いかと思い
調べてみらたいい感じのやつが見つかりました
SQL書こうかと思いましたが、active recordの機能を使えたので、
コードきれいに保つことができましたと。
1 2 3 4 5 6 7 8 9 | 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