我的模型中有这两行,是为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] }}
我正在制作PostgreSQL,但我正在使用SQLite3进行开发。如何以与数据库无关的方式编写这些行?
顺便说一句,“recorded_on”由以下内容组成:
Model.recorded_on = Time.parse("Fri, 01 May 2009 08:42:23 -0400")
答案 0 :(得分:3)
好的,发现有更好的方式(感谢this article):
在模型中基本上什么都不做!
date = Date.new(year, month, 1)
Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })
答案 1 :(得分:0)
BETWEEN应该是非常普遍的:这样的事情怎么样:
named_scope :by_month, lambda { |month|
d1 = Date.new(2009, month, 1)
d2 = d1.end_of_month
{ :conditions => ['recorded_on between ? and ?', d1, d2]}
}
named_scope :by_year, lambda { |year|
d1 = Date.new(year, 1, 1)
d2 = d1.end_of_year
{ :conditions => ['recorded_on between ? and ?', d1, d2]}
}
如果你有时间,你需要在小时,分钟和秒钟上更聪明一些。