2012-12-24 30 views
0

假設我有一個Products模型和一個Categories模型。保存常量查詢 - 導軌

我想在首頁上顯示每個類別的頂級產品。

我做這樣的事情(簡體):

# Using closure tree gem for category hierarchy 
# This returns a list of category IDs, somewhat expensive call if 
# there are a lot of categories nested within "toys" 
@categories = Category.find('toys').self_and_descendants 
@top_toys = Products.joins(:categories).where(:categories => {:id => category_ids}}).limit(5) 

我不知道這是否是最有效的方式。似乎有一種方法可以存儲那些相對不變的類別ID。

任何想法?謝謝!

回答

1

這是一個比較有效的:

@category_ids = Category.select(:id).find('toys').self_and_descendants.collect(&:id) 
@top_toys = Products.where(:category_id => @category_ids).limit(5) 

幾點:

  1. 沒有理由得到比從類別表中的類別ID以外的任何
  2. 沒有意義,加入到當您所做的只是使用category_id進行過濾時,產品類別表格

然後,您可以使用Rails緩存來存儲@categories結果,如果這不經常更改。這可能看起來像這樣

class Category < ActiveRecord::Base 

    def self.ids_for_type(category_type) 
    Rails.cache.fetch "category:#{category_type}", :expires_in => 1.day do 
     select(:id).find(category_type).self_and_descendants.collect(&:id) 
    end 
    end 

    .. 
end 

然後

@top_toys = Products.where(:category_id => Category.ids_for_type('toys')).limit(5) 

注:expires_in參數由內存緩存緩存客戶端的支持,但可能不被其他緩存提供。

+0

還應該加上'Rails.cache.clear「類別:#{} category_type」'在分類#更新和類別#創建 –

+0

我使用一個連接表,因爲他們有一個HABTM協會 – AlexBrand

+0

對於HABTM,你會需要重新加入連接,但通過僅獲取ID而不是整個類別定義,獲取類別ID的第一個查詢仍然會更快一些 –