Midnight publishing of objects & MySQL Query Cache

Usually we have to list objects that are published or expired on some day or time, for e.g. in a shop catalog, say you want to make a product available on a particular date and your conditions may look like the following in a Rails model:

  named_scope :available, lambda{
    {
      :conditions=>["products.is_available = 1 and products.available_at <= ?", Time.now.to_s(:db)]
    }
  }

MySQL has a facility to cache the results of queries and respond quickly when asked again. To make use of it, the query should be constant. In the above, the Time.now changing every second, you end up asking MySQL with different query every second. In reality, many listings can work without being too sensitive to time. You can publish at midnight without doing much harm. A simple change to Date.today.at_midnight or even the immediate hour can result in great performance of your queries:

  named_scope :available, lambda{
    {
      :conditions=>["products.is_available = 1 and products.available_at <= ?", Date.today.at_midnight.to_s(:db)]
    }
  }

About this entry