Rails-将联接与自定义名称关联一起使用 [英] Rails - Using join with custom-named associations
本文介绍了Rails-将联接与自定义名称关联一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型
class Measurement < ApplicationRecord
belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id"
end
该关联实际上是与TestStructure模型建立的,但是关联名称是检查。 没有检查表。
The association is actually made to the TestStructure model, but the association name is examination. There is no examination table.
当我使用 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我使用的是命名关联而不是
So clearly, the examinations
table doesn't exists, but I can't find a way to tell ActiveRecord I'm using a named association instead of the default one.
有什么见解?
推荐答案
其中
需要实际的表名,只需将其插入SQL中即可。
where
expects the actual table name, it just inserts it in 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应该抽象这些内容。您可以使用 merge
:
Then you depend on table name while Model should abstract such things. You could use merge
:
Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5))
这篇关于Rails-将联接与自定义名称关联一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文