Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a postgresql function in Rails

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.
like image 845
d_a_n Avatar asked Oct 21 '22 13:10

d_a_n


1 Answers

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 }
like image 166
Chris Aitchison Avatar answered Oct 27 '22 00:10

Chris Aitchison