ActiveRecord find all parents that have associated children

后端 未结 4 1502
生来不讨喜
生来不讨喜 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:37

    class SupplierCategory < AR
      has_many :supliers
    
      def self.with_supliers
        self.all.reject{ |c| c.supliers.empty? }
      end
    end
    
    SupplierCategory.with_supliers
    #=> Array of SuplierCategories with supliers
    

    Another way more flexible using named_scope

    class SupplierCategory < AR
      has_many :supliers
      named_scope :with_supliers, :joins => :supliers, :select => 'distinct(suplier_categories.id), suplier_categories.*', :having => "count(supliers.id) > 0"
    end
    
    SupplierCategory.with_supliers(:all, :limit => 4)
    #=> first 4 SupplierCategories with suppliers
    

提交回复
热议问题