I have these two lines in my model, written for PostgreSQL:
我在我的模型中有这两行,为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] }}
I'm running PostgreSQL in production, but I'm developing with SQLite3. How can I write those lines in a way that is database-agnostic?
我在生产中运行PostgreSQL,但我正在使用SQLite3进行开发。如何以与数据库无关的方式编写这些行?
Btw, "recorded_on" is formed from the following:
顺便说一下,“recorded_on”由以下内容组成:
Model.recorded_on = Time.parse("Fri, 01 May 2009 08:42:23 -0400")
2 个解决方案
#1
Okay, found out there's a better way (thanks to this article):
好的,发现有更好的方法(感谢这篇文章):
Basically do nothing in the model!
在模型中基本上什么都不做!
date = Date.new(year, month, 1)
Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })
#2
BETWEEN should be pretty universal: how about something like this:
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]}
}
If you have times, you'd need to get a little smarter with the hours, minutes and seconds.
如果你有时间,你需要用小时,分钟和秒来更聪明一点。
#1
Okay, found out there's a better way (thanks to this article):
好的,发现有更好的方法(感谢这篇文章):
Basically do nothing in the model!
在模型中基本上什么都不做!
date = Date.new(year, month, 1)
Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })
#2
BETWEEN should be pretty universal: how about something like this:
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]}
}
If you have times, you'd need to get a little smarter with the hours, minutes and seconds.
如果你有时间,你需要用小时,分钟和秒来更聪明一点。