0

I have a column that should contains the difference between created_at and updated_at in minutes, so I tried to do the following but it usually saves the time_diff with zero. So, how can I fix that?

Product.update(
    id,
    time_diff: "((EXTRACT (DAY FROM (now()-created_at))*24*60*60+
                    EXTRACT (HOUR FROM (now()-created_at))*60*60+
                    EXTRACT (MINUTE FROM (now()-created_at))*60+
                    EXTRACT (SECOND FROM (now()-created_at)))/60)::int"
  )

The Extract query works fine in SQL but it doesn't work inside activerecord's update.

Mahmoud M. Abdel-Fattah
  • 1,479
  • 2
  • 16
  • 34

2 Answers2

3

Lot of ways for time difference. You can make custom method of time difference like:

def time_diff(start_time, end_time)
  seconds_diff = (start_time - end_time).to_i.abs

  hours = seconds_diff / 3600
  seconds_diff -= hours * 3600

  minutes = seconds_diff / 60
  seconds_diff -= minutes * 60

  seconds = seconds_diff

  "#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end

And Use it

time_diff(updated_at, created_at) #just example

Or you can use ruby gem time_difference

Suneel
  • 371
  • 4
  • 14
  • I want to make it in one step when using activerecord .update... don't want to get the data and calculate the difference then save the date – Mahmoud M. Abdel-Fattah Sep 14 '15 at 09:54
  • @MahmoudM.Abdel-Fattah write a callback after_save :update_time_diff # product.rb def update_time_diff update_attributes(time_diff: (update_at - created_at)/60 ) end hopefully it will work for you. – Suneel Sep 14 '15 at 10:17
2

extract (epoch ...) gives an interval in seconds, so use:

select extract (
    epoch from now() - '2015-09-14 03:06:02.848+02'::timestamp)::int/60 
    as minutes;

 minutes
---------
       7
(1 row)
klin
  • 112,967
  • 15
  • 204
  • 232
  • Actually, the extract works fine SQL-Side but the problem is with Rails activerecord's update – Mahmoud M. Abdel-Fattah Sep 14 '15 at 09:54
  • Maybe this post could help: [How to execute a raw update sql with dynamic binding in rails](http://stackoverflow.com/questions/4483049/how-to-execute-a-raw-update-sql-with-dynamic-binding-in-rails) – klin Sep 14 '15 at 11:32