What\'s the difference between \"includes\" and \"joins\" in ActiveRecord query? Can anyone explain to me with the following two associated
:joins is the ActiveRecord version of JOINS, the SQL request.
Store.joins(:car).to_sql
=> SELECT stores.* FROM stores INNER JOIN cars ON cars.store_id = categories.id
So behind the seen it is an implicit INNER JOIN. It will thus indeed return all stores that have a car (because of the inner_join, a left_outer_join would have had a different behaviour). See more here.
Whereas :includes is not a query command. It solves the n+1 query issue by eager_loading the Car model on the Store model. See more one eager_loading here.
stores = Store.includes(:car)
will thus return all stores, and allows to do stores.first.car without firing a new query.