Search code examples
ruby-on-railsdatabase-agnostic

Rails: Making this query database-agnostic...?


I have these two lines in my model, written for PostgreSQL:

named_scope :by_month, lambda { |month| { :conditions => ["EXTRACT(MONTH FROM recorded_on) = ?", month] }}
named_scope :by_year, lambda { |year| { :conditions => ["EXTRACT(YEAR FROM recorded_on) = ?", year] }}

I'm running PostgreSQL in production, but I'm developing with SQLite3. How can I write those lines in a way that is database-agnostic?

Btw, "recorded_on" is formed from the following:

Model.recorded_on = Time.parse("Fri, 01 May 2009 08:42:23 -0400")

Solution

  • Okay, found out there's a better way (thanks to this article):

    Basically do nothing in the model!

    date = Date.new(year, month, 1)
    Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })