[英]Eager load extended has_many association
找不到任何有關如何指定與includes
參數的擴展關聯的信息。 考慮:
Class Author < ActiveRecord::Base
has_many :books do
def of_genre(genre)
where(genre: genre)
end
end
end
這可以像這樣使用: Aurhor.first.books.of_genre('horror')
。 我想將其與includes
一起使用: Author.where(...).includes(:books).where(books: ...)
這將生成左連接,但由於我的特定用例的性質,我不希望它加入到書籍表中,而是加入一個已經過濾的書籍表(因此擴展)。 這在某種程度上可能嗎?
一種可能的方法是在 Book 上創建范圍,然后在 Author 上為它們創建關聯,這將允許您 eager_load 它們,但不幸的是會產生一些開銷。
class Book < ApplicationRecord
scope :horror, -> { where(genre: "horror") }
scope :fantasy, -> { where(genre: "fantasy") }
end
class Author < ApplicationRecord
has_many :horror_books, -> { horror }
has_many :fantasy_books, -> { fantasy }
end
Author.first.includes(:horror_books)
Author.first.includes(:fantasy_books)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.