sethherr
sethherr

Reputation: 126

Rails 6.1 self referential has_many missing

Rails 6.1 added the missing method to find orphan records, but I'm struggling to apply it to a self referential has_many.

Consider this model:

class Item < ApplicationRecord
  belongs_to :parent_item, class_name: "Item"
  has_many :child_items, class_name: "Item", foreign_key: :parent_item_id
  has_many :approved_child_items, -> { approved }, class_name: "Item", foreign_key: :parent_item_id

  scope :approved, -> { where.not(approved_at: nil) }

  # This doesn't work:
  scope :no_child_items, -> { where.missing(:child_items) }
  # This doesn't work either:
  scope :no_approved_child_items, -> { where.missing(:approved_child_items) }
end

I want to find all the Items that don't have child_items.

How do I get the no_child_items and the no_approved_child_items scopes to work?

Upvotes: 1

Views: 159

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Looking at the implementation, it appears that the new method is simply a sugar for the old way (the one with left_joins), but only its simple form. With self-referential relationships you can do

.left_joins(child_items: :items)

but this seems to not be supported in missing. So, it's likely you can't use missing for this. Use left_joins instead.

Upvotes: 1

Related Questions