以下は少し不自然な例ですが、要点は理解できます。
次のモデルがあるとしましょう。
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Book < ActiveRecord::Base
has_many :chapters
has_many :comments, as: :commentable
end
class Chapter < ActiveRecord::Base
has_many :pages
has_many :comments, as: :commentable
end
class Page < ActiveRecord::Base
has_many :paragraphs
has_many :comments, as: :commentable
end
class Paragraph < ActiveRecord::Base
has_many :comments, as: :commentable
end
特定の書籍とその子孫に関するすべてのコメントを 1 回のクエリで取得することは可能ですか? つまり、本のモデルだけでなく、章、ページ、および段落に付けられたコメントも含めて、すべてのコメントが必要です。ところで、Book はモデルごとに関連付けを行い、それぞれに対して内部結合を実行できますが、これにより 4 つのクエリが発生します。
Postgres をデータベースとして使用し、Rails 3.2.12 を使用しています。