Since nobody else bothered to explain why you would use includes
vs joins
:
Assume data:
addr1 = Address.create(street: "1 Unique Street", city: "test")
addr2 = Address.create(street: "2 Unique Street", city: "test")
Location.create(name: "Location 1", address: addr1)
Joins:
Location.joins(:address).where(addresses: { city: "test" })
# performs INNER JOIN
#> [#<Location id: 1, name: "Location 1">,
#<Location id: 1, name: "Location 1">]
Includes:
Location.includes(:address).where(addresses: { city: "test" })
# performs LEFT OUTER JOIN
#> [#<Location id: 1, name: "Location 1">]
If you use joins
, use distinct
:
Location.joins(:address).where(addresses: { city: "test" }).distinct(:location)
#> [#<Location id: 1, name: "Location 1">]
The reason is because of the INNER JOIN
that joins
performs. See more information here: What is the difference between "INNER JOIN" and "OUTER JOIN"?