paint-brush
Differences Between Includes and Joins in Ruby on Railsby@ashubhosale
19,038 reads
19,038 reads

Differences Between Includes and Joins in Ruby on Rails

by ashubhosaleJune 7th, 2021
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - Differences Between Includes and Joins in Ruby on Rails
ashubhosale HackerNoon profile picture

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:

http://railscasts.com/episodes/181-include-vs-joins?autoplay=true