5

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:

  1. My database will be used by other applications other than rails and I want to define common functions that all of them can use.
  2. I'd like to control access to the data over multiple applications.
  3. It takes some of the processing away from the application server.
  4. It is more scalable if I use a lot of calculated fields.
4

1 回答 1

3
people = Person.select('*, age(date_of_birth)')
people.each { |person| puts person.age }

是的,这将添加一个age以前不存在的方法Person

您还可以将新方法别名为函数名称以外的名称:

people = Person.select('*, age(date_of_birth) as foo')
people.each { |person| puts person.foo }
于 2013-04-02T13:39:37.640 回答