caarlos0
caarlos0

Reputation: 20633

Conditional includes in Single Table Inheritance models

I have my models like this:

A < ActiveRecord::Base
- has_many :z

B < A
- has_many :y

C < A
- has_many :x

Somewhere, I want to do something like:

A.all.includes([:z,:y, :x])

But it doesn't work, because some items are from specific type B and other are C.

How can I conditionally include one or another?

Upvotes: 3

Views: 804

Answers (2)

mr_ffloyd
mr_ffloyd

Reputation: 103

A bit messy, but fully correct solution.

A.from("(#{B.includes(:y).to_sql} UNION #{C.includes(:x).to_sql}) as #{A.table_name}").includes(:z)

Upvotes: 0

caarlos0
caarlos0

Reputation: 20633

While I don't find a real fix, I'm doins this:

all = B.includes([:z, :y])
all = (all + C.includes([:z, :x])).sort_by(&:date)

It isn't that pretty, but solves the issue for the moment. Lots of speed improvement.

Thanks.

Upvotes: 2

Related Questions