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

前端 未结 6 1797
名媛妹妹
名媛妹妹 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 19:00

    stores = Store.joins(:car)
    

    This will return all stores for which there is a car. stores[0].car will result in another query.

    stores = Store.includes(:car)
    

    This will return all stores, car or no car. stores[0].car will not result in another query.

    stores = Store.includes(:car).joins(:car)
    

    This will return all stores with a car. stores[0].car will not result in another query. I wouldn't recommend this for has_many relationships, but it works great for has_one.

提交回复
热议问题