2017-08-07 96 views
3

我想在has_many/belongs_to協會類似於此示例實現includesRails的5.1:檢索記錄嵌套協會與包括

class Author < ApplicationRecord 
    has_many :books, -> { includes :line_items } 
end 

class Book < ApplicationRecord 
    belongs_to :author 
    has_many :line_items 
end 

class LineItem < ApplicationRecord 
    belongs_to :book 
end 

此刻,當我做@author.books我在控制檯中看到它加載BookLineItem並顯示記錄Book,沒有記錄LineItem。當我嘗試@author.books.line_items時出現未定義的方法錯誤。 @author.line_items也不起作用。

我該如何獲得LineItem記錄Author?謝謝!

回答

5

您需要將has_many關聯添加到Author

像這樣:has_many :line_items, through: :books, source: :line_items

然後,如果你做author.line_items,那麼你將得到作者的LineItem記錄。

您使用includes方法的方式允許您通過書籍訪問line_items。 事情是這樣的:author.books.first.line_items,這段代碼不會去到數據庫,因爲你在has_many :books, -> { includes :line_items }includes自動加載的line_items

+2

了'source'選項是在這種情況下,可選的(見https://stackoverflow.com/questions/ 4632408/need-help-to-understand-source-option-of-have-one-many-through-of-rails) – MrYoshiji

+1

謝謝你,這很不錯:)像魅力一樣工作!對於我來說,當我改變爲'source::line_items' - 似乎是複數形式。可能有錯字。 – matiss

+0

@matiss是這是一個錯字!編輯! – MatayoshiMariano