开发者

Why does my JOIN still trigger n+1 selects in active record?

开发者 https://www.devze.com 2023-04-09 11:35 出处:网络
PortfolioEngine::Portfolio Load (0.3ms)SELECT \"portfolio_engine_portfolios\".* FROM \"portfolio_engine_portfolios\" INNER JOIN \"portfolio_engine_items\" ON \"portfolio_engine_items\".\"portfolio_id\

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

The n+1 is triggered by looping through each portfolio's items.

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

I have no idea, why this happens....

@开发者_如何学运维portfolios = PortfolioEngine::Portfolio.
    joins(:items).
    order("portfolio_engine_portfolios.sort_index ASC, portfolio_engine_items.sort_index ASC").
    all


Have you tried includes instead of joins?

0

精彩评论

暂无评论...
验证码 换一张
取 消