首先,基于此( 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.co_author
- 作者.书籍
但是,有时我需要急切地加载多个作者的书籍(以避免 N 次查询)。
我正在尝试做类似的事情:
Author.includes(books: :title).where(name: ["Lewis Carroll", "George Orwell"])
Rails 5 向我抛出:“ArgumentError:关联作用域“books”依赖于实例(作用域 block 采用参数)。不支持预加载依赖于实例的作用域。”
我想弄清楚我应该做什么?
我应该使用多对多关联吗?听起来像是一个解决方案。然而,它看起来会引入它自己的问题(我需要“排序”,这意味着我需要明确区分主要作者和共同作者)。
只是想弄清楚我是否缺少一些更简单的解决方案......
最佳答案
为什么不使用 HABTM关系?例如:
# Author model
class Author < ApplicationRecord
has_and_belongs_to_many :books, join_table: :books_authors
end
# Book model
class Book < ApplicationRecord
has_and_belongs_to_many :authors, join_table: :books_authors
end
# Create books_authors table
class CreateBooksAuthorsTable < ActiveRecord::Migration
def change
create_table :books_authors do |t|
t.references :book, index: true, foreign_key: true
t.references :author, index: true, foreign_key: true
end
end
end
您可以使用 eagerload,如下所示:
irb(main):007:0> Author.includes(:books).where(name: ["Lewis Carroll", "George Orwell"])
Author Load (0.1ms) SELECT "authors".* FROM "authors" WHERE "authors"."name" IN (?, ?) LIMIT ? [["name", "Lewis Correll"], ["name", "George Orwell"], ["LIMIT", 11]]
HABTM_Books Load (0.1ms) SELECT "books_authors".* FROM "books_authors" WHERE "books_authors"."author_id" IN (?, ?) [["author_id", 1], ["author_id", 2]]
Book Load (0.1ms) SELECT "books".* FROM "books" WHERE "books"."id" IN (?, ?) [["id", 1], ["id", 2]]
关于ruby-on-rails - 两个belong_to引用同一个表+急切加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070162/