两个belongs_to引用相同的表+渴望加载

时间:2018-01-03 01:50:20

标签: ruby-on-rails ruby-on-rails-5 eager-loading belongs-to

首先,基于此(Rails association with multiple foreign keys),我想出了如何使两个belongs_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
  • author.books

但是,有时我需要为多位作者加载书籍(以避免N次查询)。

我正在尝试做类似的事情:

Author.includes(books: :title).where(name: ["Lewis Carroll", "George Orwell"])

Rails 5向我发出警告:“ArgumentError:关联范围'books'与实例有关(范围块采用参数)。不支持预加载实例相关的范围。”

我想弄清楚我应该做些什么?

我应该与多对多关联吗?这听起来像一个解决方案。然而,看起来它会引入它自己的问题(我需要“排序”,这意味着我需要明确区分主要作者和共同作者)。

试图弄清楚我是否错过了一些更简单的解决方案......

2 个答案:

答案 0 :(得分:2)

为什么不使用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]]

答案 1 :(得分:0)

试试这个:

 Author.where(name: ["Lewis Carroll", "George Orwell"]).include(:books).select(:title)