gpt4 book ai didi

ruby-on-rails - 在 Rails 中调用 Postgres 存储函数的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-29 11:29:35 26 4
gpt4 key购买 nike

我在 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"

关于ruby-on-rails - 在 Rails 中调用 Postgres 存储函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com