以下是一个人为的例子,但它会明白这一点。
假设我有以下模型。
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
是否可以通过一次查询获得特定书籍及其后代的所有评论?也就是说,我不仅想要书籍模型的所有评论,还想要对章节、页面和段落的评论。顺便说一句,我意识到这本书可以通过每个模型的关联,为每个模型执行内部连接,但这会导致 4 个查询。
我使用 postgres 作为数据库和 Rails 3.2.12。