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

Rails 5.1: retrieve records for nested association with includes

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

1
2
3
4
5
6
7
8
9
10
11
12
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也不起作用。

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


您需要将has_many关联添加到Author

像这样:has_many :line_items, through: :books, source: :line_items

然后,如果您执行author.line_items,则将获得作者的LineItem记录。

使用include方法的方式使您可以通过书本访问line_items
如下所示:author.books.first.line_items,此代码不会进入数据库,因为您在has_many :books, -> { includes :line_items }中的includes自动加载了line_items