Here's my existing code. I could use some guidance on how to optimize this. Essentially, I don't want to have to run a SQL query more than once -- self.active_item?(r). What I'm thinking I can do instead of making separate DB queries, is retrieve an array of all the user's active inventory items (e.g., self.acti开发者_如何学运维ve_inventory_items), turn that into an array of items, then query the array to see if related_item == item. What do you think?
# 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
def retrieve_owned_items(purchasing_item)
if related_items = purchasing_item.related_items
InventoryItem.all(:conditions => {:item_id => related_items.map(&:id)})
end
end
精彩评论