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

mat*_*iss 3 ruby activerecord ruby-on-rails ruby-on-rails-5.1

我试图实现包括has_many/ belongs_to类似于此示例关联:

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
Run Code Online (Sandbox Code Playgroud)

在那一刻,我做@author.books我看到我的控制台IT负载BookLineItem和显示的记录Book,没有记录LineItem.我尝试时得到未定义的方法错误@author.books.line_items.也没有@author.line_items工作.

请问如何获取LineItem记录Author?谢谢!

Mat*_*ano 5

您需要添加has_many关联Author.

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

如果你这样做author.line_items,那么你将获得LineItem作者的记录.

您使用包含方法的方式允许您line_items通过书籍访问.像这样:author.books.first.line_items这段代码不会进入数据库,因为includes你已经has_many :books, -> { includes :line_items }自动加载了line_items

  • 在这种情况下,`source`选项是可选的(参见/sf/ask/324268591/轨) (2认同)