I'm confused at how to do an active record join. 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
validates :response_limit, presence: true
class User < ApplicationRecord
has_many :responses
has_many :tasks, through: :responses
class Response < ApplicationRecord
belongs_to :task, optional: false
belongs_to :user, optional: false
In plain English, I'd like to create a query that given a query, returns all tasks that:
- Has a Response count less than the :response_limit field in Task
- The User has not responded to already.
I'm able to satisfy #2 with this nested query, which I got from an earlier question.
Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
However, I'm having difficulty satisfying the first. I took at stab at it and got this:
Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id])).where('response_limit > (?)', Response.where(task_id:task.id).count)
My issue is that I'm not sure how to get the task_id from the outer query into the Response subquery.