Reputation: 8189
I have a query like this:
PrimaryModel.includes(:associated_models)
.where(foo: true)
.where('associated_models.bar >= 0')
Typically, this would prompt ActiveRecord to join in associated_models, but instead I get this error:
ActiveRecord::StatementInvalid Exception: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "associated_models"
However, a query like this will properly join the tables:
PrimaryModel.includes(:associated_models)
.where(foo: true)
.where(associated_models: { baz: true })
Also, and perhaps most telling, this works:
PrimaryModel.includes(:associated_models)
.where(foo: true)
.where(associated_models: { baz: true })
.where('associated_models.bar >= 0')
In this last one, 'associated_models' gets joined by .where(associated_models: { baz: true })
, allowing .where('associated_models.bar >= 0')
to work properly. Anyone else experience this? Figure out a solution?
Upvotes: 0
Views: 69
Reputation: 118299
When you will be using the association name in a query as you tried, you have to say it explicitly:
PrimaryModel.includes(:associated_models)
.where(foo: true)
.where('associated_models.bar >= 0')
.references(:associated_models) # should be actual table name.
Read conditions part from doco.
But as you saw, the explicit mention is not needed when you will write it like a Hash
syntax - .where(associated_models: { baz: true })
.
Upvotes: 1