Rails:使此查询与数据库无关......?

发布于 2024-07-21 01:34:03 字数 475 浏览 4 评论 0原文

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

I have these two lines in my model, written for 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?

Btw, "recorded_on" is formed from the following:

Model.recorded_on = Time.parse("Fri, 01 May 2009 08:42:23 -0400")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心房的律动 2024-07-28 01:34:03

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]}
  }

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

BETWEEN should be pretty universal: how about something like this:

  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.

相守太难 2024-07-28 01:34:03

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

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

date = Date.new(year, month, 1)
Model.find(:all, :conditions => { :recorded_on => date..date.end_of_month })

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 })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文