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

时间:2016-03-07 22:11:18

标签: ruby-on-rails ruby activerecord

我有一个成功返回ActiveRecord结果的查询。

private void refreshRecyclerAdapter() {
        List<Items> items = getYourItems();
        ItemsRecyclerAdapter adapter = new ItemsRecyclerAdapter(getActivity(), items);
        mRecyclerView.setAdapter(adapter);
    }

以上查询返回9个结果。

我想要的是将上面获得的整个结果转换为哈希,例如:

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)

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

这应该有效:

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

解释:这里不需要实例化AR实例,所以只需运行SQL即可。使用select_rows将为您提供一个数组数组,其中外部数组的每个元素都是SQL结果中的一行。每个内部数组都有两个元素:日期和交易金额。

现在它恰好可以将一个两元素数组的数组传递给Hash[],它会将每个内部数组的第一部分解释为散列键,第二部分将作为散列值。< / p>

编辑:我假设您正在使用以下内容设置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

因此它是一个包含您要运行的SQL的字符串。

答案 1 :(得分:2)

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

theHash = Hash[*resultArray.flatten]

尚未测试:)