2017-08-29 54 views
2

加入我有以下型号导轨 - 使用带有自定义命名的协会

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的我使用了一个名为关联而不是默认的关联。

任何见解?

+2

有了'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

回答

3

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

Measurement.joins(:examination).merge(TestStructure.where(year: 2016, month: 5)) 
+0

谢谢。这条线上有多少查询? – Sebastialonso

+0

@Sebastialonso应该只有一个 –

+3

@Sebastialonso你选择的不是最好的解决方案:那么你依赖于表名,而不是取决于应该抽象的东西 –

1

在此示例中,应该提供表名examinations而不是where方法中的关联名称examination

Measurement.jons(:examination).where(examinations: { year: 2016, month: 5 }) 
+0

请纠正我,如果我错了,eager_load实际上是否将记录检索到内存中?我打算不这样做,因此加入。 – Sebastialonso

+1

@Sebastialonso:根据activerecord文档我错了,你可以使用'连接',但表名警告是至关重要的。 – potashin

4

对于加入您使用联想的名字,但对于那些需要使用表名

Measurement.joins(:examination).where(test_structures: { year: 2016, month: 5 }) 

Measurement.joins(:examination).where('test_structures.year': 2016, 'test_structures.month': 5) 
+0

是的,工作很好。谢谢! – Sebastialonso