【问题标题】:What is the best way to call a Postgres stored function in Rails?在 Rails 中调用 Postgres 存储函数的最佳方法是什么?
【发布时间】:2019-10-17 09:20:02
【问题描述】:

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

【问题讨论】:

  • 你检查this了吗?
  • ActiveRecord中没有特殊方法,需要使用SQL。你可以做类似Post.connection.execute("select version();").first
  • @nathanvda 谢谢,我做到了,但是调用first 是不够的,因为它返回了一个哈希值,我需要从中提取我的值;所以我将.values.first 添加到first,因为只返回了1 个值。您想将其发布为您的答案吗?

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

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"

【讨论】:

    猜你喜欢
    • 2015-06-24
    • 1970-01-01
    • 2017-02-11
    • 2016-09-19
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多