Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

Rails includes with where

I'm trying to eager load some associations, but I want to do filtering on some of the sub-relations here is what I mean.

class MyModel < ActiveRecord::Base
  has_many :my_model_details, dependent: :destroy
end

class MyModelDetails < ActiveRecord::Base
  belongs_to :property
  belongs_to :my_model
  belongs_to :track
  belongs_to :person
end

So if I want to get all MyModel objects which have details that belong to certain property with property name I would do this.

MyModel.includes(my_model_details: [:property, :person]).where('property.property_name = ?', 'Property name')

The reason why I want use includes instead of joins, is that I want to have my model details in grouped by the last property and person name. So I don't want to fire the N+1 query in that case.

Ex

If my query returns single MyModel object with two MyModelDetail records.

Where mymodeldetail id 1 has property id 1 and mymodeldetail id2 has property id 2. And they both belong to the same person.

So on my UI I would display this:

MyModel 1
  MyModelDetail 2 - Property name: 'some name' - Person: 'Bob'

Now what happens when I use my includes query is this :

MyModel.includes(my_model_details: [:property, :person]).where('property.property_name = ?', 'Property name')

SELECT "MY_MODEL".* FROM "MY_MODEL" WHERE (PROPERTY.PROPERTY_NAME = 'Prop')

If I use includes with where, join sql is not generated at all and so this query fails of course:

"PROPERTY"."PROPERTY_NAME": invalid identifier

Why is that, I'm using rails 4? How can I make it work with both joins and includes

Upvotes: 2

Views: 5356

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

I think it should be properties, because table name is pluralized according to CoC, try using properties.property_name instead

MyModel.includes(my_model_details: [:property, :person]).where('properties.property_name = ?', 'Property name')

As suggested by BroiSatse, add .references(:properties) to your query

Hope that helps!

Upvotes: 5

Related Questions