ActiveRecord的聚合函数:有一个数据库无关的“EXTRACT(周末从日)”? [英] ActiveRecord aggregate function: is there a database-agnostic 'EXTRACT(WEEK from date)'?
问题描述
我有一个工作得很好(有轨3和PostgreSQL)方法;我只是想知道,如果有可能,使之与数据库无关的:
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)'
据我了解,方法提取的日期,每周ISO数值总是特定数据库。
As i understand it, methods to extract a week ISO number from a date are always database-specific.
我可以使用类似虚拟属性:本周看到的此处,但似乎:组选项只接受原始的SQL。我也看到这个解决方案,但它不适合我的需要。 另一种方法是使用一个数据库视图,甚至添加:每周一栏中填用回调方法 - 但我想preFER不要惹我的模式
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.
那么,什么线索?
推荐答案
都能跟得上 - 如果你需要每周做一组,你最好直接在数据库中保存为一个额外的列通过设置 before_save
回调。
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.
正如你所说的,每周从日期提取是不平凡的,所以最好还是让Rails的处理这个问题,而不是你的数据库。这将提高性能了。
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.
更新:
例回调:
def Thing
before_save :set week
private
def set_week
self.week = self.date.cweek
end
end
这篇关于ActiveRecord的聚合函数:有一个数据库无关的“EXTRACT(周末从日)”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!