Rails 5.1:检索包含嵌套关联的记录

Rails 5.1: retrieve records for nested association with includes

我正在尝试在 has_many / belongs_to 关联中实现 includes 类似于此示例:

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 的记录,没有 [=16] 的记录=].当我尝试 @author.books.line_items 时出现未定义方法错误。 @author.line_items 也不起作用。

如何获取 AuthorLineItem 条记录?谢谢!

您需要将 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