Search code examples
ruby-on-railsactiverecorddateaggregate-functionsdatabase-agnostic

ActiveRecord aggregate function: is there a database-agnostic 'EXTRACT(WEEK from date)'?


i have a method that works just fine (with rails 3 and PostgreSQL) ; i just wonder if it's possible to make it database-agnostic :

FarmGatePrice.average :price, :group => 'EXTRACT(WEEK FROM date)'

As i understand it, methods to extract a week ISO number from a date are always database-specific.

I could use something like a virtual attribute :week as seen here, but it seems the :group options only accepts raw SQL. I've also seen this solution but it doesn't fit my needs. Another way would be to use a database view, or even to add a :week column filled by a callback method - but i'd prefer not to mess with my schema.

So, any clue ?


Solution

  • Nope - if you need to do a group by week, you're better off saving it directly in the database as an extra column set via a before_save callback.

    As you say, extracting a week from a date is non-trivial, and so it's best to let Rails handle this rather than your database. This will improve performance too.

    Update:

    Example callback:

    def Thing
    
      before_save :set week
    
      private
         def set_week
            self.week = self.date.cweek
         end
    end