重构我的代码以消除单独的数据库查询

时间:2010-07-15 03:26:04

标签: ruby-on-rails

这是我现有的代码。我可以使用一些指导如何优化它。从本质上讲,我不希望不止一次运行SQL查询 - self.active_item?(r)。我想我能做的不是单独的数据库查询,而是检索所有用户的活动库存项目的数组(例如,self.active_inventory_items),将其转换为项目数组,然后查询数组以查看related_item ==项目。你觉得怎么样?

    # User has many inventory_items.
    # Item has many inventory_items.
    # InventoryItem belongs to user, item.

# in User Model
def retrieve_owned_items(purchasing_item)
  related_items = purchasing_item.related_items # returns an array of Items (related to item user is going to purchase)

  owned_items = []
  unless related_items.nil?
    related_items.each do |r| # iterate through each related item
      if self.active_item?(r) then # runs a SQL query every time to check if the related item is currently an active item in the inventory
        owned_items << InventoryItem.find_by_item_id(r.id) # create an array of related_items already owned
      end
    end
  end

  return (owned_items.blank? ? nil : owned_items)
end

1 个答案:

答案 0 :(得分:1)

def retrieve_owned_items(purchasing_item)
  if related_items = purchasing_item.related_items
    InventoryItem.all(:conditions => {:item_id => related_items.map(&:id)})
  end
end