首页 > 解决方案 > 在 Rails 中调用 Postgres 存储函数的最佳方法是什么?

问题描述

我在 Postgres 中创建了一个函数,我想从我的 Rails 代码中调用它。最好的方法是什么?我可以使用 ActiveRecord 方法吗?还是我需要使用 SQL,例如Arel.sql

标签: ruby-on-railspostgresqlactiverecord

解决方案


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"

推荐阅读