问题
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