【问题标题】:Sql Query in rake file not showing resultrake 文件中的 Sql 查询未显示结果
【发布时间】:2020-04-27 17:50:56
【问题描述】:

我正在尝试在 rake 任务中运行此 SQL 查询,但它确实显示了任何结果。但我尝试在 Dbeaver 中运行此查询,它运行得非常好。第一个 puts 仅在终端中显示 #,而 第二个 puts 不显示任何值。请帮我找出问题。

namespace :expense do
  desc "send emails"
  task send_reminder: :environment do
  sql = <<-SQL
  SELECT
    c.id             as corporation_id
  , cs_i.id          as issue_id
  , MAX(i.id)        as expense_id
  , MAX(i."date")    as expense_date
  FROM companies c
  JOIN expenses i on i.corporation_id = c.id
  JOIN issues cs_i on i.issue_id = cs_i.id
  WHERE c.amount > 0 and 
        cs_i.amount > 0 and 
        i."date" < (select (current_date at time zone 'UTC' - interval '1 week')) and i.amount_type = 0 
  GROUP BY c.id, cs_i.id
  SQL
    scope = Expense.connection.execute(sql)
      puts "#{scope}"
    scope.each do |expense|
      puts "#{expense}"
    end    
  end
end

【问题讨论】:

    标签: sql ruby-on-rails postgresql rake


    【解决方案1】:

    如果您尝试运行原始 SQL,您可能不应该使用 connection.execute。请参阅execute 方法的文档:

    在此连接的上下文中执行 SQL 语句并从连接适配器返回原始结果。注意:根据您的数据库连接器,此方法返回的结果可能是手动内存管理的。考虑改用exec_query 包装器。

    execute 从您的连接适配器返回原始结果。例如,对于 PostgreSQL,它是 PG::Result 对象。

    您可能也不想使用exec_query,因为它还会返回某种原始结果。

    根据我在您的代码中看到的,您可能想要使用find_by_sql。它执行查询并返回标准的 ActiveRecord 对象:

    namespace :expense do
      desc "send emails"
      task send_reminder: :environment do
        sql = <<-SQL
          sql truncated...
        SQL
    
        scope = Expense.find_by_sql(sql)
          puts "#{scope}"
        scope.each do |expense|
          puts "#{expense}"
        end    
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 2022-10-20
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2013-12-16
      相关资源
      最近更新 更多