加入我有以下型號導軌 - 使用帶有自定義命名的協會
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的我使用了一個名爲關聯而不是默認的關聯。
任何見解?
有了'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