开发者

How do we know if a query is cache or retrieved from database?

开发者 https://www.devze.com 2023-01-02 14:40 出处:网络
For example: class Product has_many :sales_orders def total_items_deliverable self.sales_orders.each { |so| #sum the total }

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)开发者_C百科 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 ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消