【发布时间】:2018-02-07 09:26:01
【问题描述】:
我有以下型号
class Measurement < ApplicationRecord
belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id"
end
实际上是对TestStructure模型进行关联,但关联名称是examine。 没有检查台。
当我使用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、joins和references,您需要使用模型中定义的关系名称。对于where,您需要使用准确的表名。因此,如果您的模型TestStructure将数据存储在表custom_named_table中,则需要执行Measurement.joins(:examination).where(custom_named_table: { year: 2016, month: 5 })(您可以使用TestStructure.table_name找到表名)(请参阅我之前关于该主题的答案:stackoverflow.com/questions/24266069/…)跨度>
标签: ruby-on-rails ruby postgresql activerecord ruby-on-rails-5