Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
How to avoid n + 1 without using includes?

I have two models

class Task < AR::Base
  habtm :user_groups
end

class UserGroup < AR::Base
  habtm :tasks
end

Requirement:

t = Task.where(id: 45734)
t.user_group_ids #[54, 523, 78]

The above line will cause 2 queries.

I want to do this in one query without using includes.

My Attempt:

tasks = Task.joins(:user_groups).select('tasks.id, user_groups.id as ug_id').where(customer_id: 5)

But it is retrieving only single user group even for the tasks which has multiple groups associated.

Update

As Max suggested:

t = Task.joins('LEFT OUTER JOIN tasks_user_groups ON tasks_user_groups . analysis_task_id  =  tasks . id  INNER JOIN  user_groups  ON  user_groups . id  =  tasks_user_groups . user_group_id').select('user_groups.id').where(id: 36299)

Now i'm getting two tasks which has the same id but two different user groups.

Please suggest how to achieve it.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

.joins uses an INNER LEFT JOIN so it will only give the rows from tasks that have a match in users_groups.

.includes gets around this by using two separate queries.

What you want is instead is an outer join.

# Rails 5
Task.left_outer_joins(:user_groups)

# Rails 4
tasks = Task.joins('LEFT OUTER JOIN user_groups ON user_groups.task_id = tasks.id')

See:

What is the difference between "INNER JOIN" and "OUTER JOIN"?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!