Rails: Making this query database-agnostic…?

℡╲_俬逩灬. 提交于 2019-12-08 04:13:03

问题


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")

回答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:

  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.



来源:https://stackoverflow.com/questions/893617/rails-making-this-query-database-agnostic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!