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
How to Select Rows for a Specific Date, Ignoring Time in SQL Server
Select from One Table, Insert into Another Table Oracle SQL Query
How to Rename an Index in MySQL
How to Use Count() and Distinct Together
Sql: Search for a String in Every Varchar Column in a Database
Counting Rows for All Tables at Once
Difference Between N'String' VS U'String' Literals in Oracle
Example of Three Valued Logic in SQL Server
Calling a Function That Returns a Refcursor
How to Use Regular Expression in SQL Server
Executing a Stored Procedure Inside Begin/End Transaction
Join to Only the "Latest" Record with T-Sql
Will a SQL Server Job Skip a Scheduled Run If It Is Already Running
Limit Results from Joined Table to One Row
Equals(=) VS. Like for Date Data Type
Custom Order by to Ignore 'The'