Differences Between Includes and Joins in Ruby on Rails | Hacker Noon

@ashubhosaleashubhosale

I am here to write about my experiences and how I learnt from my experiences.

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

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.

read original article here