anonn023432
anonn023432

Reputation: 3120

Inconsistent attribute reference in `exists?` method in Rails

This is my User model:

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

In method upcoming_events_in, it correctly looks for start attribute on the events record, but it attempts to look for duration on the User instance. Is there a way to tie it to the events instance?

Upvotes: 0

Views: 53

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

I have no idea about Rails but it can be easily performed with plain old good 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 version:

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

Or like, I don’t have PG to check.

Upvotes: 3

Related Questions