title: How to optimize and reduce database calls?
body: <p>I'm calculating totals on the fly for a project but it is currently quite database intensive:</p>
  
  <pre><code>def sub_total(package)
    subtotal = 0.0
    self.quote_items.order("area_id").each do |item|
      subtotal += Unit.find(item.unit_id).highest_price(package)*item.quantity if item.unit
    end
    sprintf("%.2f", sub_total)
  end
  </code></pre>
  
  <p>In Unit model:</p>
  
  <pre><code>def highest_price(package)
    highest_price = 0
    highest_id = 0
    self.options.where("options.id IN (SELECT option_id FROM options_packages WHERE package_id = '#{package.id}')").each do |option|
      if (option.price &gt; highest_price)
        highest_price = option.price
        highest_id = option.id
      end
    end
    Quote.add_margin highest_price
  end
  </code></pre>
  
  <p>At each iteration, it queries the database in the Unit.find method.</p>
  
  <p>How can this be optimised?  I'd appreciate any help or advice to clean this up!  This project uses Rails 3.0.9 and Ruby 1.8.9.</p>