What's the difference between “includes” and “joins” in ActiveRecord query?

前端 未结 6 1798
名媛妹妹
名媛妹妹 2020-12-15 18:37

What\'s the difference between \"includes\" and \"joins\" in ActiveRecord query? Can anyone explain to me with the following two associated

6条回答
  •  悲哀的现实
    2020-12-15 18:41

    :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.

提交回复
热议问题