Sobes.tech
Middle

What is the difference between Joins and Includes in Ruby on Rails?

sobes.tech AI

Answer from AI

joins is used to perform SQL JOIN operations to select data based on relationships between tables, but only loads columns of the main model.

includes is used to solve the N+1 query problem. It performs either a single SQL query with a LEFT OUTER JOIN (if there are no conditions on included associations), or two SQL queries (one for the main model, another for related models) to load all related data along with the main model, avoiding multiple additional queries.

Key differences:

  • Purpose: joins - filtering/selecting based on relationships; includes - optimizing loading of related data (N+1).
  • SQL query: joins - usually an INNER JOIN (but can be others); includes - LEFT OUTER JOIN or two separate queries.
  • Data loading: joins - loads only the main model, related data is not accessible without additional queries; includes - loads the main model and related models.
  • Access to related data: After joins, accessing related data triggers additional queries. After includes, accessing related data does not trigger additional queries.
# Example of using joins
# Find users who have at least one post
User.joins(:posts)
# Example of using includes
# Load all users and their posts with one or two queries
User.includes(:posts).each do |user|
  user.posts.each do |post|
    # Access to post without additional query
    puts post.title
  end
end

Choosing between joins and includes depends on the task: if you just need to filter main model records based on related data, use joins. If you need to retrieve the main model along with related data for subsequent use without N+1 problems, use includes.