0

I'm working on a project dealing with opening hours of a store. I have Store and OpeningHour models, (Store has_many OpeningHour). The opening_hours table has day, start and end fields to store the day that OpeningHour record is to apply to, the time the store opens and the time the store closes.

What would be the best way of finding any records where the time range set by start and end fields covers Time.now?

Similar to the below conceptually:
OpeningHour.where((start..end).cover? Time.now)

Any help would be much appreciated!

simonlehmann
  • 852
  • 1
  • 10
  • 27
  • Do you mean something like [this](https://stackoverflow.com/a/12404927/5239030)? – iGian May 04 '18 at 13:15
  • @iGian Thanks for your response. Yes, very similar to this, however the [accepted answer](https://stackoverflow.com/a/12404927/5328443) relies on all 3 fields being in the database. In my car, the range boundaries are database fields, but the value to check is a variable. – simonlehmann May 04 '18 at 13:33
  • 1
    Did you try `OpeningHour.where("start <= ? AND end >= ?", Time.now, Time.now)`? – iGian May 04 '18 at 14:01
  • What type are the `start` and `end` columns declared as? You should also note that `end` is not a good column name for a rails app as `end` is a keyword in ruby. Use `ends_at` instead. – max May 04 '18 at 16:55
  • @max The fields are of the `time` datatype. Thanks for the tip on the keyword. I'll fix that! – simonlehmann May 05 '18 at 03:31
  • The answer will depend a bit on what database is in use since you need to extract the hours and minutes from the time for the comparison. – max May 05 '18 at 09:04

0 Answers0