按月份编号查找特定月份的所有记录(例如 1 = 1 月)



使用 Rails 4.2, Ruby 2.1.7.Postgresql 9.4

我想找到特定月份的所有记录,当我只有一个整数作为参数时。

例如 1 = 一月,2 = 二月

现在我有(start_time是我的datetime领域)

def self.by_month(month)
  where('extract(month from start_time) = ?', month)
end

生成的 SQL 查询为:

SELECT "jobs".* FROM "jobs" WHERE (extract(month from start_time) = 1)

更好的解决方案可能是使用一系列日期。ActiveRecord 将其转换为WHERE x BETWEEN y AND z因为如果您有几年的记录,提取月份可能会模棱两可。

像这样:

def self.by_month(int)
  int = int - 1 # convert month from 1 to 0 based
  now = DateTime.now
  if int < (now.month + 1) # now.month is 1 based
    min = now.beginning_of_year + int.months
  else
    min = now.last_year.beginning_of_year + int.months
  end
  where(start_time: [min..(min.end_of_month)])
end

您的确切方法最终如何取决于您如何处理可能落入前一年或下一年的月份。

在某些情况下,让用户选择带有日期输入的月份可能更有意义,以便您可以区分。

相关内容

最新更新