我有以下型号
class Measurement < ApplicationRecord
belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id"
end
该关联实际上是与 TestStructure 模型进行的,但关联名称是 exam。没有检查台。
当我使用查询时出现问题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 我正在使用命名关联而不是默认关联。
有什么见解吗?
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 https://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-merge:
Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)