ActiveRecord查询比较时间间隔

时间:2016-12-23 18:48:34

标签: ruby-on-rails ruby-on-rails-4 activerecord

如何使用ActiveRecord执行此类操作?

Reservation.where("start..finish < 1 hour")

开始完成是时间记录:

2.2.1 :009 > Reservation.last.start.class
  Reservation Load (1.1ms)  SELECT  "reservations".* FROM "reservations"  ORDER BY "reservations"."id" DESC LIMIT 1
  Reservation Load (1.1ms)  SELECT  "reservations".* FROM "reservations"  ORDER BY "reservations"."id" DESC LIMIT 1
 => ActiveSupport::TimeWithZone 

感谢。

2 个答案:

答案 0 :(得分:2)

如果你正在使用Postgres,你可以使用其中一个time and date functions

Reservation.where("(finish - interval '1 hour') < start")

答案 1 :(得分:0)

@reservationsWithinInterval1 = Reservation.where('startdate >= ? AND startdate < ? , @reservation.startdate, @reservation.enddate)

@reservationsWithinInterval2 = Reservation.where('enddate >= ? AND enddate < ?, @reservation.startdate, @reservation.enddate)

然后检查是否

if @reservationsWithinInterval1.count > 0 || @reservationsWithinInterval2.count>0
flash[:notice] = 'Select different time. Car already reserved in this time'