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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With