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时,我在控制台中看到它加载了Book和LineItem并显示了Book的记录,而没有LineItem的记录。尝试@author.books.line_items时出现未定义的方法错误。 @author.line_items也不起作用。
如何获取Author的LineItem条记录?谢谢!
您需要将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
- 在这种情况下,source选项是可选的(请参阅stackoverflow.com/questions/4632408/…)
-
谢谢,这很好:)就像魅力一样!对我来说,当我改为source: :line_items时,它似乎可以工作-就像复数一样。也许那里有错字。
-
@matiss是的,这是一个错字!编辑!