2016-06-12 8 views
1

私は私のアプリを持っているもののn + 1クエリの問題を見つけるために弾丸の宝石を使用していて、それは私が3つの問題持っ判明:は含まれています - Railsの

をユーザー:Rashed N + 1クエリが検出されましたショップ=> [:ショッピングモール] ファインダーに追加: :含ま=> [:モール]ユーザー:ラシッドN + 1クエリ 検出ショップ=> [:カテゴリ]あなたのファインダーに追加します:含ま=> [:カテゴリ]

問題は、モデルがお互いにどのように関連付けられているのかにかかわらず、インクルードを使って問題を解決する方法を本当に分かりません。私は4つのモデル、セール、ショップ、モール、カテゴリーを持っています。これらは私のモデルのための団体です:すべての売上レコードを表示する私の販売インデックスページで

class Shop < ActiveRecord::Base 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 
    has_many :mall_shops 
    has_many :malls, :through => :mall_shops 
    has_many :sales, dependent: :destroy 
end 

class Sale < ActiveRecord::Base 
    belongs_to :shop 
end 

class Mall < ActiveRecord::Base 
    has_many :mall_shops 
    has_many :shops, :through => :mall_shops 
    has_many :sales, :through => :shops 
end 

class Category < ActiveRecord::Base 
    has_many :categorizations 
    has_many :shops, :through => :categorizations 
    has_many :sales, :through => :shops 
end 

、IM、および各販売レコードは店に属し、各店舗が多くのカテゴリと多くのショッピングモールがあります。すべての販売記録について、その販売店が属するすべてのモールおよびカテゴリを(フィルター目的で)反復表示しています。

<% @sales.each do |sale| %> 
    <div class="<% sale.shop.malls.each do |m| %> mall<%= m.id %><% end %><% sale.shop.categories.each do |c| %> category<%= c.id %><% end %>"> 

. 
. 

end 

そして、私の販売のコントローラー:これは、関連する私の販売のインデックスページ内のコードである

class SalesController < ApplicationController 
def index 
    @malls = Mall.all.order('name ASC') 
    @categories = Category.all.order('category_type ASC') 
    @shops = Shop.all 
    @sales = Sale.where('offer_end >= ?', Date.today).order('offer_end ASC') 
    end 
end 

だから何が私が持っているN + 1つのクエリ問題を解決するための最良の方法だろうか?このウェブサイトのイムの建物である私のアプリのより良いアイデアを得るために:コントローラでwww.shopwatchkw.com

答えて

2

、これを試してみてください。

@sales = Sale.includes(shop: [:categories, :malls]) 
      .where('offer_end >= ?', Date.today) 
      .order('offer_end ASC') 

は基本的に、あなたはあなたの最上位モデルで開始しています子どもたちをincludesステートメントで熱心に読み込んでいます。 Bulletが.includes(:shop)を追加するように指示してから、その後、:categories:mailsについて同じことを教えてくれました。これはShopのサブクエリです。

Read more on eager loading in Rails

+0

これは問題を解決しました、ありがとう! :) –

関連する問題