Activerecord find records by time in datetime

ε祈祈猫儿з 提交于 2019-12-23 03:09:13

问题


I am trying to perform an active record query that returns records by time by looking in the datetime field. Specifically I want to get all records that were created between 1am and 6am, not caring what day they were created just making sure that the time falls within the range.

So if i had records:

1: car=> "Honda", color: "blue", created_at => "2014-11-13 01:15:00"
2: car=> "Toyota", color: "red", created_at => "2014-11-17 04:15:00"
3: car=> "Honda", color: "red", created_at => "2014-11-20 10:15:00"

The first and second records should be returned.


回答1:


To do this directly you'll need to resort to a splash of vendor-specific SQL.

e.g.:

  • postgresql: Car.where('extract(hour from created_at) between 1 and 6')
  • mysql: Car.where('hour(created_at) between 1 and 6')

This won't be fast on a large table, however, unless you can index on the expression. If you are using MySQL, e.g., you might want to store the hour in a separate column so you can index on it. Then the condition would also simplify to Car.where(created_hour: 1..6).



来源:https://stackoverflow.com/questions/27138478/activerecord-find-records-by-time-in-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!