0

Sorry if this has been posted elsewhere, not sure what to search for.

I have this query that is currently using .select, but there must be a better way to get the same result without using the dreaded .select? The mission is: find all shift cancellations that were created within 6 hours of when the shift was supposed to start:

ShiftCancellation.select{|c| c.created_at > c.shift.date_time - 6.hours}

ShiftCancellation belongs_to :shift and vice versa.

I'm on Postgres, so SQL-exclusive queries won't work.

mantralux
  • 33
  • 3

2 Answers2

0

You can join to the other table to allow all fields to be queried, but I'm not sure what the best way to get the date - 6hours is. I think DATE_SUB may be what you need:

ShiftCancellation.joins(:shift).where("shift_cancellations.created_at > DATE_SUB(shifts.date_time, INTERVAL 6 HOUR)"}

Bunch of examples here: https://stackoverflow.com/a/1888569/385532

Matt
  • 13,948
  • 6
  • 44
  • 68
0

Solved it.

ShiftCancellation.joins(:shift).where("shift_cancellations.created_at > (shifts.date_time - interval '6 hours')")
mantralux
  • 33
  • 3