简体   繁体   English

如何将activerecord结果转换为哈希?

[英]How to convert activerecord result into a hash?

I have a query that returns results in ActiveRecord successfully. 我有一个查询,该查询成功返回ActiveRecord中的结果。

select
    trunc(b.transaction_date) as transaction_date,
    sum(a.transaction_amount) as transaction_amount
from
  payment_transaction a,
  payment_settlement b
where
    a.transaction_status = 'S'
    and b.settlement_type = 'D'
    and trunc(b.transaction_date) > sysdate - 30
    and a.payment_transaction_id = b.payment_transaction_id
group by
    trunc(b.transaction_date)
order by
    trunc(b.transaction_date)

The above query returns 9 results. 上面的查询返回9个结果。

What I want is to convert the entire result obtained above into a hash such as: 我想要的是将上面获得的整个结果转换为哈希,例如:

{
"01/01/16" => 764.00, 
"02/01/16" => 1508.00, 
"03/01/16" => 2000.00 
..
..
..
}

How can I achieve this? 我该如何实现?

This should work: 这应该工作:

Hash[ActiveRecord::Base.connection.select_rows(sql)]

To explain: there is no need to instantiate AR instances here, so just run your SQL. 解释一下:这里不需要实例化AR实例,因此只需运行SQL。 Using select_rows will give you an array of arrays, where each element of the outer array is one row from the SQL result. 使用select_rows将为您提供一个数组数组,其中外部数组的每个元素都是SQL结果的一行。 Each inner array has two elements: the date and the transaction amount. 每个内部数组都有两个元素:日期和交易金额。

Now it just happens you can pass an array of two-element arrays to Hash[] , and it will interpret the first part of each inner array as the hash key, and the second part as the hash value. 现在,您可以将两个元素的数组传递给Hash[] ,它将每个内部数组的第一部分解释为哈希键,第二部分解释为哈希值。

EDIT: I'm assuming you are setting sql with something like this: 编辑:我假设您正在用这样的东西设置sql

sql = <<-EOQ
    select
        trunc(b.transaction_date) as transaction_date,
        sum(a.transaction_amount) as transaction_amount
    from
      payment_transaction a,
      payment_settlement b
    where
        a.transaction_status = 'S'
        and b.settlement_type = 'D'
        and trunc(b.transaction_date) > sysdate - 30
        and a.payment_transaction_id = b.payment_transaction_id
    group by
        trunc(b.transaction_date)
    order by
        trunc(b.transaction_date)
EOQ

So that it is a string containing the SQL you'd like to run. 这样它是一个包含您要运行的SQL的字符串。

resultArray = yourQueryResult.map{|e| [e["transaction_date"], e["transaction_amount"]]}.

theHash = Hash[*resultArray.flatten]

Haven't tested :) 还没测试过:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM