【发布时间】:2018-06-12 16:50:34
【问题描述】:
首先,基于这个(Rails association with multiple foreign keys)我想出了如何让两个belong_to指向同一张表。
我有类似的东西
class Book < ApplicationRecord
belongs_to :author, inverse_of: :books
belongs_to :co_author, inverse_of: :books, class_name: "Author"
end
class Author < ApplicationRecord
has_many :books, ->(author) {
unscope(:where).
where("books.author_id = :author_id OR books.co_author_id = :author_id", author_id: author.id)
}
end
一切都好。我可以做任何一个
- book.author
- book.co_author
- 作者.books
但是,有时我需要为多个作者急切加载书籍(以避免 N 次查询)。
我正在尝试做类似的事情:
Author.includes(books: :title).where(name: ["Lewis Carroll", "George Orwell"])
Rails 5 向我抛出:“ArgumentError: 关联范围 'books' 依赖于实例(范围块接受参数)。不支持预加载依赖于实例的范围。”
我想知道我应该怎么做?
我应该使用多对多关联吗?这听起来像是一个解决方案。但是,它看起来会引入它自己的问题(我需要“排序”,这意味着我需要明确区分主要作者和共同作者)。
只是想弄清楚我是否缺少一些更简单的解决方案......
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 eager-loading belongs-to