我有一组模型,与 railsguides 中的示例完全一样:
class Document < ActiveRecord::Base
has_many :sections
has_many :paragraphs, through: :sections
end
class Section < ActiveRecord::Base
belongs_to :document
has_many :paragraphs
end
class Paragraph < ActiveRecord::Base
belongs_to :section
end
他们提到你可以这样做 @document.paragraphs
,它使用 JOIN,但你不能反向操作...... @paragraph.document
只是不起作用。我知道使用 delegate
,但它仍然使用相同数量的查询。
有没有一种方法可以使用 joins() 或 includes() 或其他方法来做到这一点?处理此类关联的最佳方式是什么?
最佳答案
在您的 Controller 中,假设您正在查询一组文档。然后重要的是你使用 includes
来预先加载你正在经历的两个关联:
@paragraphs = Paragraph.includes(:section => :document).where(:attribute => attribute)
然后在您看来您可以执行此操作而不必担心会进行太多查询:
<% @paragraphs.each do |paragraph| %>
<%= paragraph.section.document %>
<% end %>
如果您想使用 delegate
使其更简洁并且能够编写 paragraph.document
,您仍然可以从预先加载中受益。
关于mysql - 有多少是反向通过的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19172010/