Rails中“ exists?”方法中的属性引用不一致

时间:2018-07-03 14:43:59

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

这是我的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实例?

1 个答案:

答案 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要检查。