3

我有一組模型,這正是像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,但它仍然使用相同數量的查詢。

有沒有辦法我可以用連接()或包含()或其他方式做到這一點?處理這樣的關聯的最佳方式是什麼?

回答

0

在你的控制器中,假設你正在查詢一組文檔。

@paragraphs = Paragraph.includes(:section => :document).where(:attribute => attribute) 

,然後在視圖中,可以做到這一點,而不必擔心做了太多的查詢:那麼您使用includes躍躍欲試負載兩會你正在經歷重要的

<% @paragraphs.each do |paragraph| %> 
    <%= paragraph.section.document %> 
<% end %> 

如果您想使用delegate使其更加清潔,並且能夠編寫paragraph.document,您仍然可以從急切的加載中受益。