Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

class Car < ActiveRecord::Base
  belongs_to :store
end

class Store < ActiveRecord::Base
  belongs_to :owner
  has_one :car
end
like image 465
Mellon Avatar asked Sep 09 '25 15:09

Mellon


1 Answers

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.

like image 77
Michiel de Mare Avatar answered Sep 13 '25 16:09

Michiel de Mare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!