我正在使用Rails實施在線應用程序商店。其數據模型如下圖所示:優化Rails中的購買查詢
class User < ActiveRecord::Base
has_many purchase_records
has_many items, :through => purchase_records
end
class Item < ActiveRecord::Base
has_many purchase_records
has_many users, :through => purchase_records
end
class PurchaseRecord < ActiveRecord::Base
belongs_to :user
belongs_to :item
end
它具有顯示可用的項目頁面,有價格,如果用戶已經購買的商品,價格將是一個下載鏈接,就像應用程序商店一樣。一個視圖助手可幫助產生這樣的聯繫:
def download_link(item)
# generate a download link
end
def item_link(item)
if current_user and current_user.items.where(:id => item.id).first != nil
# User already purchased it
download_link(item, 'book-price')
else
# Not purchased yet, show price and link to its details
link_to item.price, item
end
end
current_user
由色器件定義。它可以很好地工作,除了需要20個額外的數據庫查詢才能處理20個項目的頁面,因爲它需要檢查用戶是否已經爲每個項目購買了項目。我想知道它是否可以優化,例如,預先加載購買的當前用戶的項目,但我不知道如何在視圖助手中編寫它。
感謝您的意見。我在問題中添加了數據模型。 – capistrano 2012-02-04 03:44:11