2017-02-21 109 views
1

我有兩個模型:PatientCodeStatusRails:查詢零has_one關聯

CodeStatus belongs_to患者,和患者has_one CodeStatus

我想查詢所有的患者,其中patient.code_status爲零。我很驚訝地發現,Patient.where(code_status: nil)不起作用拋出:column patients.patient_id does not exist

我已經找到this (fairly old) answer,但我覺得很難相信,查詢這個最好的方法是通過原始SQL長長的一串。我認爲鐵軌會包括這個幫手,就像他們爲許多其他協會一樣。有誰知道一個不太詳細的解決方案嗎?提前致謝。

+0

幾個問題:1)'Patient.primary_key'和'CodeStatus.primary_key'的輸出是什麼? 2)爲什麼查詢以patient.patient_id列開頭?默認情況下,它應該期望主鍵爲'patient.id' ... 3)你可以將整個has_one/belongs_to行添加到你的問題中嗎?你是否將任何選項傳遞給這些方法? 4)你可以爲這兩個表添加db/schema嗎? – Glyoko

+1

'支持where(column:nil)',並用postgres生成'WHERE「表。」「column_name」IS NULL'。你可能搞砸了關聯定義。如果'CodeStatus'屬於'Patient','CodeStatus'必須有'patient_id'列。 – nicooga

回答

3

的問題是,

patient.code_status 

不是列,但在方法,通過當你說

class Patient 
    has_one :code_status 
end 

這裏是你如何讓不相關聯的所有患者的Rails添加任何代碼狀態:

Patient.includes(:code_status).where(code_statuses: { id: nil })