【问题标题】:Rails 5.1: retrieve records for nested association with includesRails 5.1:检索包含嵌套关联的记录
【发布时间】:2017-08-07 16:42:44
【问题描述】:

我正在尝试在类似于此示例的 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 的记录,没有LineItem 的记录。尝试@author.books.line_items 时出现未定义的方法错误。 @author.line_items 也不起作用。

请问如何获取AuthorLineItem 记录?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-5.1


    【解决方案1】:

    您需要将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, -&gt; { includes :line_items } 中的includes 自动加载了line_items

    【讨论】:

    • source 选项在这种情况下是可选的(请参阅stackoverflow.com/questions/4632408/…
    • 谢谢,这很好:) 像魅力一样工作!对我来说,当我更改为 source: :line_items 时,它似乎起作用了——就像复数一样。可能有错别字。
    • @matiss 是的,这是一个错字!已编辑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多