Rails: How to get objects with at least one child?

后端 未结 6 1157
星月不相逢
星月不相逢 2021-01-03 21:10

After googling, browsing SO and reading, there doesn\'t seem to be a Rails-style way to efficiently get only those Parent objects which have at leas

6条回答
  •  孤独总比滥情好
    2021-01-03 21:15

    You just want an inner join with a distinct qualifier

    SELECT DISTINCT(*) 
    FROM parents
    JOIN children
    ON children.parent_id = parents.id
    

    This can be done in standard active record as

    Parent.joins(:children).uniq
    

    However if you want the more complex result of find all parents with no children you need an outer join

    Parent.joins("LEFT OUTER JOIN children on children.parent_id = parent.id").
    where(:children => { :id => nil })
    

    which is a solution which sux for many reasons. I recommend Ernie Millers squeel library which will allow you to do

    Parent.joins{children.outer}.where{children.id == nil}
    

提交回复
热议问题