Skip to content

Unable to query a model where 2 associations use the same model #1011

@jwoertink

Description

@jwoertink

Related: #1007

Say you have a model where it has 2 belongs_to and both of those associations are the same model (e.g. User), any query you do that requires both will only use 1 join and override any where clauses set.

class Interview < BaseModel
  table do
    belongs_to interviewer : User
    belongs_to interviewee : User
  end
end

# I want to query for all interviews where the Interviewer isn't available for hire, but the Interviewee is
InterviewQuery.new
      .where_interviewer(UserQuery.new.available_for_hire(false))
      .where_interviewee(UserQuery.new.available_for_hire(true))

In this case, we end up getting this SQL which is not what I want

SELECT interviews.*
FROM interviews
INNER JOIN users ON interviews.interviewer_id = users.id
WHERE users.available_for_hire = 'false'
  AND users.available_for_hire = 'true'

My initial thought is if we just always alias the joins to your association method name, then maybe it'll fix this. However, I think that may also be a breaking change for anyone using where(raw_query : String).

So where_interviewer would go from

INNER JOIN users ON interviews.interviewer_id = users.id

to

INNER JOIN users AS interviewers ON interviews.interviewer_id = interviewers.id

But then anyone that was doing where("users.something @> ?", ...) would now get runtime errors since they would need to change it to where("interviewers.something @> ?", ...).

Maybe we can use some annotation to turn on this change at compile time and give people time to swap over? I'm not sure how that would work. 🤔

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions