我正在尝试在rake任务中运行此SQL查询,但它确实显示任何结果。但是我尝试在Dbeaver中运行此查询,它运行得很好。第一个puts仅在终端中显示#,而second 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,则可能不应该使用connection.execute
。请参阅execute
方法的文档:
在此连接的上下文中执行SQL语句,并从连接适配器返回原始结果。注意:根据数据库连接器的不同,此方法返回的结果可能是手动进行内存管理的。考虑改用
execute
包装器。
exec_query
返回来自连接适配器的原始结果。例如,对于PostgreSQL,它是execute
对象。
您可能也不想使用PG::Result
,因为它也会返回某种原始结果。
根据我在您的代码中看到的,您可能想使用exec_query
。它执行查询并返回标准的ActiveRecord对象:
find_by_sql