0
0
RailsHow-ToBeginner · 4 min read

How to Use Joins in Rails: Syntax and Examples

In Rails, use joins to combine records from two or more tables based on their associations. The joins method accepts association names or SQL strings to perform INNER JOINs, allowing you to query related data efficiently.
📐

Syntax

The joins method in Rails is used to perform SQL INNER JOINs between tables. You can pass it:

  • Symbol or array of symbols: Names of associations defined in your models.
  • String: Raw SQL join clauses for custom joins.

Example: Model.joins(:association_name) joins the model's table with the associated table.

ruby
User.joins(:posts)
User.joins(:posts, :comments)
User.joins("INNER JOIN profiles ON profiles.user_id = users.id")
💻

Example

This example shows how to get all users who have posts using joins. It joins the users table with the posts table through the association.

ruby
class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
end

# Fetch users with posts
users_with_posts = User.joins(:posts).distinct

users_with_posts.each do |user|
  puts "User: #{user.name}"
end
Output
User: Alice User: Bob
⚠️

Common Pitfalls

Common mistakes when using joins include:

  • Using joins without selecting distinct records, causing duplicates.
  • Passing incorrect association names causing errors.
  • Expecting joins to load associated records (it only joins tables, use includes for eager loading).

Wrong usage example:

User.joins(:unknown_association)

Correct usage:

User.joins(:posts)
ruby
User.joins(:unknown_association) # raises error

User.joins(:posts) # works correctly
📊

Quick Reference

UsageDescription
Model.joins(:association)Performs INNER JOIN using model association
Model.joins(:assoc1, :assoc2)Joins multiple associations
Model.joins("SQL JOIN clause")Custom SQL join
Model.joins(:assoc).distinctAvoid duplicate records after join

Key Takeaways

Use joins to combine tables based on model associations with INNER JOIN.
Pass association names as symbols or raw SQL strings to joins.
Use distinct with joins to avoid duplicate records.
joins does not eager load data; use includes for that.
Always verify association names to prevent errors.