为什么我的JOIN仍会在活动记录中触发n + 1选择?

时间:2011-09-30 20:29:56

标签: activerecord

PortfolioEngine :: Portfolio Load(0.3ms)SELECT“portfolio_engine_portfolios”。* FROM“portfolio_engine_portfolios”INNER JOIN“portfolio_engine_items”ON“portfolio_engine_items”。“portfolio_id”=“portfolio_engine_portfolios”。“id”ORDER BY portfolio_engine_portfolios.sort_index ASC, portfolio_engine_portfolios.sort_index ASC,portfolio_engine_items.sort_index ASC

PortfolioEngine :: Item Load(0.2ms)SELECT“portfolio_engine_items”。* FROM“portfolio_engine_items”WHERE“portfolio_engine_items”。“portfolio_id”= 2 ORDER BY portfolio_engine_items.sort_index ASC,sort_index asc

PortfolioEngine :: Item Load(0.3ms)SELECT“portfolio_engine_items”。* FROM“portfolio_engine_items”WHERE“portfolio_engine_items”。“portfolio_id”= 3 ORDER BY portfolio_engine_items.sort_index ASC,sort_index asc

PortfolioEngine :: Item Load(0.2ms)SELECT“portfolio_engine_items”。* FROM“portfolio_engine_items”WHERE“portfolio_engine_items”。“portfolio_id”= 1 ORDER BY portfolio_engine_items.sort_index ASC,sort_index asc

通过循环遍历每个投资组合的项目来触发n + 1。

class Portfolio < ActiveRecord::Base
  has_many :items,
         order: "portfolio_engine_items.sort_index asc",
         autosave: true,
         inverse_of: :portfolio
  default_scope :order => 'portfolio_engine_portfolios.sort_index ASC'
end

class Item < ActiveRecord::Base
  belongs_to :portfolio
  belongs_to :client
  has_many :images,
           order: "sort_index ASC",
           autosave: true,
           inverse_of: :item
end

我不知道,为什么会发生这种情况......

@portfolios = PortfolioEngine::Portfolio.
    joins(:items).
    order("portfolio_engine_portfolios.sort_index ASC, portfolio_engine_items.sort_index ASC").
    all

1 个答案:

答案 0 :(得分:1)

您是否尝试过includes而不是joins