Kyle Decot
Kyle Decot

Reputation: 20835

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?

Upvotes: 3

Views: 1254

Answers (2)

istern
istern

Reputation: 99

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"

Upvotes: 0

Lars Haugseth
Lars Haugseth

Reputation: 14881

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)

Upvotes: 5

Related Questions