我有以下型号 class Measurement ApplicationRecord belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id"end 该关联实际上是对TestStructure模型进行的,但关联名称是检查.没有检查表. 当我
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...
很明显,考试表不存在,但是我找不到告诉ActiveRecord我使用命名关联而不是默认关联的方法.
任何见解?
如果需要实际的表名,只需将其插入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 })
但这并不好
然后你依赖于表名,而Model应该抽象这样的东西.你可以使用合并:
Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5))