ActiveRecord find all parents that have associated children

后端 未结 4 1519
生来不讨喜
生来不讨喜 2020-12-09 20:16

I don\'t know why I can\'t figure this out, I think it should be fairly simple. I have two models (see below). I\'m trying to come up with a named scope for SupplierCatego

4条回答
  •  遥遥无期
    2020-12-09 20:45

    Here is one more approach:

    named_scope :with_suppliers, :include    => :suppliers, 
                                 :conditions => "suppliers.id IS NOT NULL"
    

    This works because Rails uses OUTER JOIN for include clause. When no matching rows are found the query returns NULL values for supplier columns. Hence NOT NULL check returns the matching rows.

    Rails 4

    scope :with_suppliers, { includes(:steps).where("steps.id IS NOT NULL") }
    

    Or using a static method:

    def self.with_suppliers
      includes(:steps).where("steps.id IS NOT NULL")
    end
    

    Note:

    This solution eager loads suppliers.

    categories = SupplierCategory.with_suppliers
    categories.first.suppliers #loaded from memory
    

提交回复
热议问题