【问题标题】:find all records for specific month by its month number (e.g. 1 = January)按月份编号查找特定月份的所有记录(例如 1 = 一月)
【发布时间】:2016-02-05 05:07:07
【问题描述】:

使用 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)

【问题讨论】:

  • 格式在这里很重要。尝试以yyyy/mm/dd 格式创建。
  • @Pavan 月份的格式?如何创建Date.new
  • 显示一些示例数据和您正在运行的 SQL 查询。还有month 变量的数据类型是什么。那应该是一个整数,因为extract() 返回一个整数
  • 好的,那么Feb 1st 00:00 是什么意思?这是您的输入数据吗?帮助我了解你,这样我才能帮助你。我没有找到你卡住的地方。

标签: ruby-on-rails postgresql activerecord


【解决方案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

您的具体方法最终如何取决于您希望如何处理可能属于上一年或下一年的月份。

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

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多