Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 按月份编号查找特定月份的所有记录(例如1=一月)_Ruby On Rails_Postgresql_Activerecord - Fatal编程技术网

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

Ruby on rails 按月份编号查找特定月份的所有记录(例如1=一月),ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,使用Rails 4.2、Ruby 2.1.7。Postgresql 9.4 我想查找特定月份的所有记录,当我只有一个整数作为参数时 e、 g.1=一月,2=二月 现在我有(开始时间是我的datetime字段) 生成的SQL查询是: SELECT "jobs".* FROM "jobs" WHERE (extract(month from start_time) = 1) 更好的解决方案可能是使用一系列日期。ActiveRecord将其转换为,其中y和z之间的x,因为如果您有几年的记录,提取月份

使用Rails 4.2、Ruby 2.1.7。Postgresql 9.4

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

e、 g.1=一月,2=二月

现在我有(开始时间是我的
datetime
字段)

生成的SQL查询是:

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

更好的解决方案可能是使用一系列日期。ActiveRecord将其转换为
,其中y和z之间的x
,因为如果您有几年的记录,提取月份可能是不明确的

大概是这样的:

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
def self.by_月(int)
int=int-1#基于1将月份转换为0
now=DateTime.now
如果int<(now.month+1)#now.month以1为基础
最小值=现在开始年份+整数月份
其他的
最小值=现在。最后一年。开始年+整数个月
结束
式中(开始时间:[最小…(最小月结束)])
结束
您的确切方法最终如何取决于您希望如何处理上一年或下一年可能出现的月份


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

这里的格式很重要。尝试以
yyyy/mm/dd
格式创建。@是否为月份设置格式?如何创建日期。新建?显示一些示例数据和正在运行的SQL查询。另外,
month
变量的数据类型是什么。这应该是一个整数,因为
extract()
返回一个整数,那么
Feb 1st 00:00
是什么意思?这是你的输入数据吗?帮助我了解你,这样我才能帮助你。我不会让你陷入困境,让我们走吧。
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