ActiveRecord find all parents that have associated children

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

    I believe it would be something like

    #model SupplierCategory
    named_scope :with_suppliers, 
       :joins => :suppliers,
       :select => "distinct(supplier_categories), supplier_categories.*",
       :conditions => "suppliers.supplier_categories_id = supplier_categories.id"
    

    Let me know if it works for you.

    Edit: Using fl00r's idea:

    named_scope :with_suppliers, 
       :joins => :suppliers,
       :select => "distinct(supplier_categories), supplier_categories.*",
       :having => "count(supliers.id) > 0"
    

    I believe this is the faster way.

提交回复
热议问题