【发布时间】:2016-01-08 00:51:50
【问题描述】:
我有 4 个模型:模型 1 与模型 2 相关联,模型 2 与模型 3 相关联。模型 2 和 3 通过多态关联与模型 4 相关联。这一切都有效。我无法指定模型 1 和模型 4 之间的关联,因此它们以两种方式相关:
- 模型 1 - 模型 2 - 模型 4
- 模型 1 - 模型 2 - 模型 3 - 模型 4
您将在下面找到所有关联,除了模型 1 和模型 4 之间的关联:
作者模型:
has_many :books, dependent: :destroy
图书模型:
belongs_to :author
has_many :chapters, dependent: :destroy
has_many :titles, as: :titlesource, # Polymorphic Association
dependent: :destroy
章节模型:
belongs_to :book
has_many :titles, as: :titlesource, # Polymorphic Association
dependent: :destroy
标题模型:
belongs_to :titlesource, polymorphic: true
问题:假设您有上述关联,并且您想知道author 具有的titles,无论它们是书名还是章节名。我应该使用哪些关联来扩展上述设置? (我假设有has_many through)
更新:如果我要寻找的只是书名,我希望将 has_many :titles, through: :books 添加到 Author 模型中会起作用。但事实并非如此。如果我添加该关联,则Author.first.titles 会产生错误undefined method 'titles'。我认为这与多态关联和命名有关......?我做错了什么?
章节标题就更难了。该关联通过Book 模型,然后通过Chapter 模型,然后到Title 模型。如何在作者模型中包含这些标题?我认为它必须是具有以下逻辑的代码(但显然这段代码是不正确的):
has_many :titles, through: :books && :books:chapters
更新:给出的两个答案使用 SQL。这些解决方案不会向数据库发送大量查询,如果经常使用该方法会导致问题吗?这些方法中的一种在性能上是否优于另一种?
【问题讨论】:
-
不完全是
book has many chapterschapters has many titles现在从书中你可以包含Book.include({:chapters => :titles})的标题 -
不确定这就是我要找的。我想要一个
author的所有titles的列表。title要么与book或chapter有关系,但chapter与author没有方向关系,因此通过book。 -
所以这是第一作者的标题
Author.first.books.map(&:titles) -
@RajarshiDas 展开 =)
-
has_many :books, -> {includes :titles}在作者上现在它将加载带有标题的书籍
标签: ruby-on-rails ruby associations