我做了一件可怕的事...
我有一个包含帐户余额的表格。它具有account_id,金额和month_end日期的属性。我想查询该表以获取过去十二个月的余额。但是,没有比这更好的方法了。
scope :recent_balances, lambda { { :conditions =>
["month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ?",
last_month_end.to_s,
(last_month_end-1.month).end_of_month.to_s,
(last_month_end-2.month).end_of_month.to_s,
(last_month_end-3.month).end_of_month.to_s,
(last_month_end-4.month).end_of_month.to_s,
(last_month_end-5.month).end_of_month.to_s,
(last_month_end-6.month).end_of_month.to_s,
(last_month_end-7.month).end_of_month.to_s,
(last_month_end-8.month).end_of_month.to_s,
(last_month_end-9.month).end_of_month.to_s,
(last_month_end-10.month).end_of_month.to_s,
(last_month_end-11.month).end_of_month.to_s ] } }
private
def self.last_month_end
last_month_end ||= (Date.today - 1.month).end_of_month
end
我的问题是:
months = (1..11).map { |m| last_month_end.advance(months: 0 - m) }
where("month_end IN (?)", months)
或类似的东西。这将是您进行上述操作时更具可读性和可维护性的方式。就像其他人所说的,您可以检查SQL中的日期是否在开始日期和结束日期之间。
where("date >= ? AND date <= ?", start_date, end_date)
或(更好)
where("date BETWEEN ? AND ?", start_date, end_date)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句