I have the following model
class Measurement < ApplicationRecord
belongs_to :examination, class_name: "TestStructure", foreign_key: "examination_id"
end
The association is actually made to the TestStructure model, but the association name is examination. There is no examination table.
The problem arises when I'm querying using join
. The following query
Measurement.joins(:examination).where(examination: { year: 2016, month: 5 })
fails, with this error
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...
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.
Any insights?
includes
,joins
andreferences
you need to use the relation name as defined in your model. Withwhere
you need to use the exact table name. So if your modelTestStructure
store data in the tablecustom_named_table
, you need to doMeasurement.joins(:examination).where(custom_named_table: { year: 2016, month: 5 })
(you can find the table name usingTestStructure.table_name
) (see my previous answers on that subject: #24266569) – Jd