查询created_at小时

时间:2012-06-30 17:25:54

标签: ruby-on-rails

如何查询在某个小时创建的记录?我是否需要在数据库中为每条记录添加一小时列? Ruby将为created_at.hour返回一个很好的值,但我不能在如下的查询中使用它:

results = Record.where("created_at.hour = ?", the_hour) 

2 个答案:

答案 0 :(得分:2)

尝试:

results = Record.where("hour(created_at) = ?", the_hour) 

您需要使用MySQL hour函数从时间戳中提取小时。

答案 1 :(得分:0)

仅供将来参考。

如果您碰巧使用SQLite,其中hour函数从时间戳中提取小时数不可用,请使用此解决方案。

def find_record_by_created_at_hour(certain_hour)
  Record.all.select {|record| record.created_at.hour == certain_hour }
end
相关问题