1

我的模型中有这两行,是为 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")
4

2 回答 2

4

好的,发现有更好的方法(感谢这篇文章):

在模型中基本上什么都不做!

date = Date.new(year, month, 1)
Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })
于 2009-05-21T19:46:43.023 回答
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]}
  }

如果你有时间,你需要在小时、分钟和秒方面变得更聪明一些。

于 2009-05-21T16:30:42.777 回答