我已经在Postgres中创建了一个函数,我想从我的Rails代码中调用它。最好的方法是什么?我可以使用ActiveRecord方法吗?还是像Arel.sql
一样需要使用SQL?
ActiveRecord中没有特殊方法,您需要使用SQL。您可以执行类似>>的操作
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"}
这将返回每行的哈希值,其中键是列名,值是对应的值。因此,对于此特定示例,我知道它只会返回一行,因此我要执行
first
立即检索第一行。如果您只想立即检索版本,也可以编写
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"