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负载Book
和LineItem
和显示的记录Book
,没有记录LineItem
.我尝试时得到未定义的方法错误@author.books.line_items
.也没有@author.line_items
工作.
请问如何获取LineItem
记录Author
?谢谢!
您需要添加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