nao
nao

Reputation: 1188

Complicated join in ActiveRecord

I'm having an issue with a tricky ActiveRecord query.

I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false

I'm trying to write a query that says, given a user_id, get all tasks where there is no Response from that User linked to it.

So if User 1 is querying, and he only has a Response to task 1, he should see all tasks except task 1.

Upvotes: 0

Views: 82

Answers (2)

Vane Trajkov
Vane Trajkov

Reputation: 768

One possible solution is to use a subquery to select all Task records that the User has Response to and they will be excluded from the main query. This will give you all Task records that the User (params[:user_id]) doesn't have Response to

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))

Upvotes: 1

Ritesh Ranjan
Ritesh Ranjan

Reputation: 1012

Try this:

Task.where('user_id != (?)', User.find(user_id).responses)

or

Task.joins(:responses).where('responses.user_id != (?)', User.find(user_id))

Upvotes: 1

Related Questions