Rails: Making this query database-agnostic…?

廉价感情. 提交于 2019-12-06 22:12:42

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

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.

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