Difference between .includes and .joins

Can somebody tell me what the difference between .includes and .joins is please?

Thanks

The tl;dr version is:

  • includes causes the associated models to be loaded into memory by ruby
  • joins does not eager load the associated models into memory.


Using includes tells rails that you want to eager load the models from that association. If you’re familiar with SQL, then you can think of this as a LEFT OUTER JOIN of all included tables. For performance reasons it’s not always actually implemented this way (it’s usually several queries that you can see in your development log), but thats the effect. The key is that all of the results are then eager loaded into memory. You would use this when you expect to iterate on all of the associated children in the view, for instance.

Using joins will perform an INNER JOIN on the tables by default. This means only rows that have a matching record in the named associated table will be returned. You can modify the default behavior by having it do a LEFT OUTER JOIN instead. Either way, the associated objects will not be loaded into memory by Ruby. joins is therefor useful when you want to limit a query by including conditions on columns from other tables but do not actually need the related objects to be in memory.

Hope this helps…

3 Likes