I'm using subclasses in mongoid and I would like to eager load relations of both the parent and its subclasses.
class Event
include Mongoid::Document
belongs_to :modifier
end
class Fixture < Event
belongs_to :club
end
When I run Event.includes(:modifier, :club)
I get:
Mongoid::Errors::InvalidIncludes:
Problem:
Invalid includes directive: Event.includes(:modifier, :club)
Summary:
Eager loading in Mongoid only supports providing arguments to
Event.includes that are the names of relations on the Event model,
and only supports one level of eager loading. (ie, eager
loading associations not on the Event but one step away via
another relation is not allowed.
Resolution:
Ensure that each parameter passed to Event.includes is a valid name
of a relation on the Event model. These are: "modifier".
The error message is reasonable but I'd like to know if there is a workaround, short of running a separate query on each class?
I'd like to be able to also chain further criteria, i.e. Event.includes(:modifier, :club).desc(:updated_at)
rather than sorting the result array in rails.
versions: Mongoid v3.16 & Rails 3.2.15
Edit: I'd better make it clearer what it is I want.
I want all events and all fixtures documents.
I also want all their relations: the modifiers on Events and Fixtures, and the clubs on Fixtures.
And I want those related documents to be retrieved from mongo all at once, i.e. typically done through 'eager loading' using the '.includes()' method .
There will be further subclasses, i.e. class Election < Events
, class Seminar < Events
. So I'd like to avoid querying each subclass separately.
I'd also like to chain further criteria, such as desc(:updated_at)
.