Let's say we have these models
class Message
belongs_to :messageable, polymorphic: true
end
class Ticket
has_many :messages, as: :messageable
has_many :comments
end
class User
has_many :messages, as: :messageable
has_many :ratings
end
class Rating
belongs_to :user
end
class Comment
belongs_to :ticket
end
Now I want to load all messages (which have associated tickets
or users
), and eager load depending on the type of class, either comments
for tickets
and ratings
for users
Of course Message.includes(:messageable).order("created_at desc")
will only include the directly associated object, but the question would be how to include the different association types that derive from each model type (i.e. in this example, how to eager load comments for tickets
and ratings for users
)?
This is just a simple example, but what about even more complicated cases, where I'd like to include something else for the user
, another association, and what if that association needs more includes?