Differences Between Includes and Joins in Ruby on Rails

Written by ashubhosale | Published 2021/06/07
Tech Story Tags: ruby-on-rails | activerecord | refactoring | ruby | programming | coding | development | code

TLDR Many of us know about includes, joins but sometimes we confuse about their usage. As I was experimenting with code refactoring in one of my projects, there I have tried these things. As we know includes and join are used when we are performing operations on associated tables. Both are used for the same purpose. When we want to fetch data along with an associated table then includes must be used.Joins: Uses lazy loading. Includes: Uses eager loading, When. We can use joins when we. want to consider the data as a condition from the joined table.via the TL;DR App

Many of us know about includes, joins but sometimes we confuse about their usage. As I was experimenting with code refactoring in one of my projects, there I have tried these things. So I thought I can share these findings with you guys.
As we know includes and join are used when we are performing operations on associated tables. Both are used for the same purpose.
Includes: Uses eager loading, When we want to fetch data along with an associated table then includes must be used.
Joins: Uses lazy loading. We can use joins when we want to consider the data as a condition from the joined table but not using any attributes from the table.
I will show you an example where includes is preferred instead of joins, also I have benchmarked both the queries so that you can see which is faster!!!

class Item < ApplicationRecord
 belongs_to :user

end

class User < ApplicationRecord
  has_many :items, dependent: :destroy
end
Now I want to display the item title with the user's first name.
Using includes the query output will be,
puts Benchmark.measure {
items = Item.includes(:user)
items.each do |item|
 item.title
 item.user.first_name
end
}
Using joins query output will be,
puts Benchmark.measure {
items = Item.joins(:user)
items.each do |item|
 item.title
 item.user.first_name
end
}
So it's self-explanatory, that include is preferred. But if we want to have items where user_id: 1, and we are not displaying any data from User table, then only use joins, because this will not load any user's data until we want(lazy load). As given below.
items = Item.joins(:user).where(user_id: 1)
items.each do |item|
 item.title
end
Below are some reference links. You can watch them for your understanding:

Written by ashubhosale | I am here to write about my experiences and how I learnt from my experiences.
Published by HackerNoon on 2021/06/07