Rails Includes with Conditions

Using Rails includes with conditions on children

You need to use LEFT JOIN.

Parent.joins("LEFT JOIN children ON parent.id = children.parent_id")
.where("parent.age = 10 AND children.age = 10")
.select("parent.*, children.*")

If you want to select rows from the parent table which may or may not have corresponding rows in the children table, you use the LEFT JOIN clause. In case there is no matching row in the children table, the values of the columns in the children table are substituted by the NULL values.

includes with where clause in ActiveRecord

You want to select where groups.shop_id is 1 or where there is no groups.shop_id

You can do that with a test for nil

Organisation.where(name: 'my organisation without groups').includes(:groups).where(groups: { shop_id: [nil, 1] })


Related Topics



Leave a reply



Submit