Kei*_*ett 5 postgresql activerecord ruby-on-rails
我在Postgres中创建了一个函数,该函数想从我的Rails代码中调用。最好的方法是什么?我可以使用ActiveRecord方法吗?还是我需要使用SQL Arel.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"}
Run Code Online (Sandbox Code Playgroud)
这将返回每行的哈希值,其中键是列名,值是相应的值。因此,对于这个特定的示例,我知道这只会返回一行,因此我会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"
Run Code Online (Sandbox Code Playgroud)