Calculating the average days between records in Rails
Given that I have a Foo model w/ the standard Rails timestamp columns what would be the most efficient way to calculate the average number of days between records being created?
The maximum and minimum class methods of your model will use the SQL aggregate functions min() and max() to find the extreme values efficiently.
span_secs = Foo.maximum(:created_at) - Foo.minimum(:created_at) avg_secs = span_secs / (Foo.count - 1) avg_days = avg_secs / (24 * 60 * 60)
If you use MySQL
secs = Foo.where("created_at IS NOT NULL").average("UNIX_TIMESTAMP(created_at)").to_i DateTime.strptime secs.to_s, "%s"