0

I' m building a rails application where I use action mailer. I wanna be able to send email per say 2 hours before a certain event.

def notification(user, event)
  @user = user
  @event = event
  @delivery_time = @event.start_at - INTERVAL '2 hour' 

  mail( to: @user.email,
  subject: "Upcoming event")
end

event.start_at is timestamp format.

would it be possible to do

 event.start_at - INTERVAL - '2 hours'

I know you can do something like that into postgresql

 timestamp '2001-09-28 23:00' - interval '23 hours'

according to Postgresql .

intro__codes
  • 172
  • 9
  • 1
    http://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby – Richard May 24 '16 at 07:15
  • 3
    Rails support datetime methods like `2.hours`, `4.days`, `5.minutes` etc... so you can use `@event.start_at - 2.hours` – x6iae May 24 '16 at 07:23

1 Answers1

0

Like sundayAdefila mentioned in their comment, you can simply do:

event.start_at - 2.hours

To find events starting in the next 2 hours, you can write an ActiveRecord query as,

Event.where(start_at: Time.now..Time.now + 2.hours)

Even better way for the above(as suggested in the comment below):

Event.where(start_at: Time.now..2.hours.from_now) 

which will be converted into an SQL query like:

SELECT `events`.* FROM `events` WHERE (`events`.`start_at` BETWEEN '2016-05-24 11:01:34' AND '2016-05-24 13:01:34')
tekina
  • 571
  • 10
  • 21
  • 1
    You can also write `2.hours.from_now` which is the same as `Time.now + 2.hours`. http://api.rubyonrails.org/classes/ActiveSupport/Duration.html#method-i-from_now – Rob May 24 '16 at 11:19