これらのモデルがあるとしましょう
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
ここで、すべてのメッセージ(tickets
またはに関連付けられているusers
)をロードし、クラスのタイプに応じて、またはのいずれかで熱心にロードcomments
しtickets
ますratings
。users
もちろんMessage.includes(:messageable).order("created_at desc")
、直接関連付けられたオブジェクトのみが含まれますが、問題は、各モデルタイプから派生するさまざまな関連付けタイプをどのように含めるか(つまり、この例では、ロードを熱心に行う方法comments for tickets
とratings for users
)ですか?
user
これは単純な例ですが、さらに複雑なケースで、別のアソシエーションに何か他のものを含めたい場合はどうでしょうか。また、そのアソシエーションにさらに多くのインクルードが必要な場合はどうでしょうか。