簡體   English   中英

如何在 Rails 關聯中急切加載關聯?

[英]How to eager load association on association in Rails?

我有這樣的系統:

class Tag < ActiveRecord::Base
  # attr :name
end

class Article < ActiveRecord::Base
  has_many :tag_associations, dependent:  :destroy
  has_many :tags, through: :tag_associations
end

class Company < ActiveRecord::Base
  has_many :articles
end


class User < ActiveRecord::Base
  belongs_to :company
end

我想這樣做:

user.company.articles.includes(:tags).all

在進行文章查詢時,會急於加載所有標簽嗎? 如果不是,我如何急切加載每篇文章的標簽,以便在我這樣做時它不是 N+1 查詢:

company.articles.all.select do |article|
  article.tags.any? do |tag|
    tag.name == 'foo'
  end
end

像這樣嵌套急切加載。

@company = user.company.includes(articles: :tags).all

@company.articles.all.select do |article|
  article.tags.any? do |tag|
    tag.name == 'foo'
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM