Reputation: 317
I have a table in postgres with date_of_birth and would like to use the Postgres age function to return the age, rather than calculate the age in Rails (this is a simple example, I will want to do more complicated calculations in postgres).
What is the best way to get the age back from postgres with the rest of my record, ideally as standard without having to modify every select?
EDIT:
I've decided to use views because:
Upvotes: 5
Views: 1526
Reputation: 4654
people = Person.select('*, age(date_of_birth)')
people.each { |person| puts person.age }
Yes, this will add a method, age
, that did not previously exist on Person
You can also alias the new method to something other than the function name:
people = Person.select('*, age(date_of_birth) as foo')
people.each { |person| puts person.foo }
Upvotes: 3