ruby-on-rails - 在 Rails 中调用 Postgres 存储函数的最佳方法是什么?
问题描述
我在 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"}
这将返回每行的哈希,其中键是列名,值是相应的值。所以对于这个特定的例子,我知道这只会返回一行,所以我会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"
推荐阅读
- linux - 如果第 n 列包含特定单词,如何删除行?
- heroku - Heroku 免费计划上的微服务应用程序
- jquery - 使用jquery触发与spotfire控制元素链接的铁python脚本
- r - 如何从列中提取部分数据并使用 R 将其粘贴到另一列中?
- python-3.x - 如何在pycharm中自动执行同一程序?
- c++ - 包含在自制静态库头文件中使用的库
- c# - ASP.net Identity - 获取“admin”或“adminlower”角色的用户集合
- javascript - Javascript检查三个值是否在2的容差范围内相等
- c# - 如何在不使用 ASP.NET 的情况下在 C# 中创建 REST 服务
- android - 如何将 SQLite 数据库中的标记输出到 MapView 和 Google Map