Calculating Average Days Between Rails Entries

Given that I have a model Foowith standard Rails timestamp columns, what would be the most efficient way to calculate the average number of days between created posts?

+3
source share
2 answers

The methods of the class maximumand minimumyour model will use aggregated SQL functions min()and max()to efficiently find extreme values.

span_secs = Foo.maximum(:created_at) - Foo.minimum(:created_at)
avg_secs = span_secs / (Foo.count - 1)
avg_days = avg_secs / (24 * 60 * 60)
+5
source

If you are using MySQL

secs = Foo.where("created_at IS NOT NULL").average("UNIX_TIMESTAMP(created_at)").to_i
DateTime.strptime secs.to_s, "%s"
0
source

Source: https://habr.com/ru/post/1524220/


All Articles