I have two models: Patient
and CodeStatus
.
CodeStatus belongs_to
Patient, and Patient has_one
CodeStatus
I am trying to query all patients where patient.code_status
is nil. I was surprised to find that Patient.where(code_status: nil)
does not work throwing: column patients.patient_id does not exist
I have already found this (fairly old) answer, but I find it difficult to believe that the best way to query this is via a long string of raw SQL. I would think that rails would include this helper like they do for many other associations. Does anyone know of a less verbose solution to this? Thanks in advance.
The problem is, that
patient.code_status
is not a column, but a method, added by Rails when you say
class Patient
has_one :code_status
end
Here is how you'd get all patients not associated with any code status:
Patient.includes(:code_status).where(code_statuses: { id: nil })