2015-09-22 52 views
1

我試圖獲得提交了esas_assessment的uniq patients的列表,按esas_assessmentcreated_at的時間排序;爲clinicianhas_manypatients:through的表稱爲care_group_assignmentsPG :: UndefinedTable:錯誤:使用SELECT DISTINCT ON時丟失表的FROM-clause條目

我在這裏是工作,但停止工作時,我就使clinicianshas_many :esas_assessments, :through => :patients而不必 esas_assessmentclinician_id場和直接綁在臨牀醫生。我需要做出這樣的選擇,以便多位臨牀醫生可以與esas_assessment相關聯。

這是我改變esas_assessments是如何與clinicians關聯過的。這是基於this answer

<% @esas_assessments.order("patient_id, created_at DESC").select('ON (patient_id) *').uniq.limit(99).each_with_index do |esas_assessment, index| %> 

現在,這給了我:

PG::AmbiguousColumn: ERROR: ORDER BY "patient_id" is ambiguous

,我實在不明白,爲什麼這些都是模糊的,因爲既不patientsclinicians有場patient_idcreated_at

爲了試圖解決這個我用this answer和曖昧的領域之前添加esas_assessment.

<% @esas_assessments.order("esas_assessment.patient_id, esas_assessment.created_at DESC").select('ON (esas_assessment.patient_id) *').uniq.limit(99).each_with_index do |esas_assessment, index| %> 

這給了我錯誤:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "esas_assessment"

: SELECT DISTINCT ON (esas_assessment.patient_id) * FROM "esas_assessments" 
INNER JOIN "patients" ON "esas_assessments"."patient_id" = "patients"."id" 
INNER JOIN "care_group_assignments" 
ON "patients"."id" = "care_group_assignments"."patient_id" 
WHERE "care_group_assignments"."clinician_id" = $1 
ORDER BY esas_assessment.patient_id, esas_assessment.created_at DESC LIMIT 99 

我一直在使用this answer,因爲它似乎是一個類似的問題,但找不出它也試過。

任何幫助將是偉大的。

的Rails 4.1.8,紅寶石2.2.1p85,PostgreSQL的

回答

4

我相信你只是缺少你的表名的s

<% @esas_assessments.order("esas_assessments.patient_id, 
    esas_assessments.created_at DESC") 
    .select('ON (esas_assessments.patient_id) *') 
    .uniq.limit(99).each_with_index do |esas_assessment, index| %> 

表名是esas_assessments,不esas_assessment

+0

一種完美的簡單的答案 - 謝謝。你知道爲什麼它沒有在列名之前加上'esas_assessments.'而模棱兩可嗎? – Skiapex

+0

那麼,我認爲'@ esas_assessments'已經被一些查詢填充了。也許這個查詢就會從另一個表'patient_id',所以當你試圖在以前使用''order'它ActiveRecordRelation'抱怨說,它不知道哪個'patient_id'你正在談論。 但無論如何這只是一個猜測。 =] – MurifoX

相關問題