Search code examples
sqlruby-on-railsaggregate-functionssqueel

Using NOW() in a select with Squeel


I want to get the average of the difference between the current time and a datetime value in the database with Squeel:

Car.select{average(NOW() - created_at)}

Which tries to take "NOW" as a column in the database:

ActiveRecord::StatementInvalid: PGError: ERROR:  column cars.NOW does not exist
LINE 1: SELECT avg("cars"."NOW" - "cars"."created_at") FROM "cars"  ...

Any way to do this in Squeel?


Solution

  • Per Ernie Miller's answer here: https://github.com/ernie/squeel/issues/112

    Car.select{average(now.func - created_at)}