2017-08-29 55 views
2

加入我有以下型號導軌 - 使用帶有自定義命名的協會

class Measurement < ApplicationRecord 
    belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id" 

end 

協會實際上是在TestStructure模型製作,但聯想的名字是考試。 沒有檢查表。

問題出現在我使用join查詢時。下面的查詢

Measurement.joins(:examination).where(examination: { year: 2016, month: 5 }) 

失敗,這個錯誤

ActiveRecord::StatementInvalid: 
    PG::UndefinedTable: ERROR: missing FROM-clause entry for table "examination" 
    LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati... 
# --- Caused by: --- 
# PG::UndefinedTable: 
# ERROR: missing FROM-clause entry for table "examination" 
# LINE 1: ...d" = "measurements"."examination_id" WHERE "examinati... 

所以很明顯,在examinations表不存在,但我不能找到一種方法來告訴ActiveRecord的我使用了一個名爲關聯而不是默認的關聯。

任何見解?

+2

有了'includes','連接「和」引用「,您需要使用模型中定義的關係名稱。用'where'你需要使用確切的表名。因此,如果您的模型TestStructure將數據存儲在表custom_named_table中,則需要執行Measurement.joins(:examination).where(custom_named_table:{year:2016,month:5})'(您可以找到表名稱使用'TestStructure.table_name')(請參閱我以前的答案關於該主題:https://stackoverflow.com/questions/24266069/join-multiple-tables-with-active-records/24266583#24266583) – MrYoshiji

回答

3

where預計實際的表名,它只是將它插入SQL:

Article.where(whatever: {you: 'want'}).to_sql 
=> "SELECT `articles`.* FROM `articles` WHERE `whatever`.`you` = 'want'" 

所以,你可以使用:

Measurement.joins(:examination).where(test_structures: { year: 2016, month: 5 }) 

但它不是好

然後你依賴於表名,而模型應該抽象這樣的事情。你可以使用merge

Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5)) 
+0

謝謝。這條線上有多少查詢? – Sebastialonso

+0

@Sebastialonso應該只有一個 –

+3

@Sebastialonso你選擇的不是最好的解決方案:那麼你依賴於表名,而不是取決於應該抽象的東西 –

1

在此示例中,應該提供表名examinations而不是where方法中的關聯名稱examination

Measurement.jons(:examination).where(examinations: { year: 2016, month: 5 }) 
+0

請糾正我,如果我錯了,eager_load實際上是否將記錄檢索到內存中?我打算不這樣做,因此加入。 – Sebastialonso

+1

@Sebastialonso:根據activerecord文檔我錯了,你可以使用'連接',但表名警告是至關重要的。 – potashin

4

對於加入您使用聯想的名字,但對於那些需要使用表名

Measurement.joins(:examination).where(test_structures: { year: 2016, month: 5 }) 

Measurement.joins(:examination).where('test_structures.year': 2016, 'test_structures.month': 5) 
+0

是的,工作很好。謝謝! – Sebastialonso