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

纵然是瞬间 提交于 2019-12-11 22:24:25

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/6537351/activerecord-aggregate-function-is-there-a-database-agnostic-extractweek-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!