views:

30

answers:

1

For example:

class Product
  has_many :sales_orders

  def total_items_deliverable
    self.sales_orders.each { |so| #sum the total }
    #give back the value
  end
end

class SalesOrder
  def self.deliverable
    # return array of sales_orders that are deliverable to customer
  end
end
  1. SalesOrder.deliverable #give all sales_orders that are deliverable to customer
  2. pa = Product.find(1)
  3. pa.sales_orders.deliverable #give all sales_orders whose product_id is 1 and deliverable to customer
  4. pa.total_so_deliverable

The very point that i'm going to ask is: how many times SalesOrder.deliverable is actually computed, from point 1, 3, and 4, They are computed 3 times that means 3 times access to database

so having total_so_deliverable is promoting a fat model, but more database access. Alternatively (in view) i could iterate while displaying the content, so i ends up only accessing the database 2 times instead of 3 times.

Any win win solution / best practice to this kind of problem ?

A: 

Look in your environment log (e.g. log/development.log) if the query is a cache you'll see:

CACHE (0.0ms)   SELECT * FROM `widgets`....

or

Widget Load (0.4ms)   SELECT * FROM `widgets`....

for a database query.

Patrick Klingemann
thank you. Is there any specific rule when such query is cache and when such query is (re)loaded from database
Hadi
I believe each unique query that runs during a request is cached so that subsequent queries that match in the same request become cache hits, rather than database queries. Keep an eye on the log to test for sure, for more info, rails query cache is the term to search for.
Patrick Klingemann