这是我的User
模型:
class User
def upcoming_events_in(minutes, client_id)
events.where(client_id: client_id).exists?(start: (Time.zone.now - duration)..(Time.zone.now + minutes))
end
end
在方法upcoming_events_in
中,它正确地在start
记录中寻找events
属性,但是它尝试在duration
实例中寻找User
。有没有办法将其绑定到events
实例?
答案 0 :(得分:3)
我对Rails
一无所知,但是可以使用普通的老式SQL轻松执行:
def upcoming_events_in(minutes, client_id)
events.
where(client_id: client_id).
where('DATEDIFF(events.start, DATESUB(NOW(), INTERVAL events.duration MINUTES)) > 0').
where('DATEDIFF(events.start, DATEADD(NOW(), INTERVAL events.minutes MINUTES)) < 0').
exists?
end
PostgreSQL 版本:
def upcoming_events_in(minutes, client_id)
start = "(TIMESTAMP events.start, TIMESTAMP events.start + INTERVAL '1 MINUTE')"
interval = "(NOW() - INTERVAL 'events.duration MINUTES', NOW() + INTERVAL 'events.minutes MINUTES')"
events.
where(client_id: client_id).
where("#{start} OVERLAPS #{interval}").
exists?
end
或者,我没有PG要检查。