What is the best way to call a Postgres stored function in Rails?

Viewed 145

I've created a function in Postgres that I'd like to call from my Rails code. What is the best way to do that? Is there an ActiveRecord method I can use? Or do I need to use SQL, as in Arel.sql?

1 Answers

There is no special method in ActiveRecord, you need to use SQL. You can just do something like

Post.connection.execute("select version();").first 
=> {"version"=>"PostgreSQL 10.5 on x86_64-apple-darwin17.7.0, compiled by Apple LLVM version 9.1.0 (clang-902.0.39.2), 64-bit"}

This will return a hash per row where the keys are the column-names, and the values the corresponding values. So for this specific example, I know this will only return one row so I do first to retrieve the first row immediately. If you would just want to retrieve the version immediately, you could also write

version = Post.connection.execute("select version();").first.values.first 
=> "PostgreSQL 10.5 on x86_64-apple-darwin17.7.0, compiled by Apple LLVM version 9.1.0 (clang-902.0.39.2), 64-bit"
Related