加入我有以下型号导轨 - 使用带有自定义命名的协会
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