0

I am using the following queries in a customer model call to obtain my desired set of transactions.

  transactions = sub_account.transactions
  transaction_items = transactions.map{|transaction| [transaction.transaction_items]}

However, this is returning an array of an array of hashes. From the rails console

[ [# <TransactionItem id: 29, amount: 20>, #<TransactionItem id: 35, amount: 40>],<br>
  [# <TransactionItem id: 31, amount: 30>, #<TransactionItem id: 38, amount: 30>],<br>
  [# <TransactionItem id: 43, amount: 30>, #<TransactionItem id: 21, amount: 40>],<br>
]

This process works well. But now I am trying to run a where query on transaction_items but can't becuase they're embedded in the array. Here is my final desired query that I am unable to run.

transaction_items.where(:amount => 30).sum("amount")

I know you can Zip an array, but can you unzip it? I can't find any documentation on it. If no unzip, can I adapt the where query to work on the embedded arrays?

Thanks.

Josh_Katz
  • 127
  • 7

1 Answers1

1

What about:

transactions_items = []
transactions.each{|n|transactions_items = transactions_items.concat(n.transaction_items)}

Assuming that transactions.transactions_items is an array. .each applies the block to each item, which concats the transactions_items of the current element n to the array transactions_items.

and

sum = 0
toSum = transactions_items.where(:amount => 30)
toSum.each{|transaction_item|sum += transaction_item.amount}

or

sum = 0
toSum = transactions_items.where(:amount => 30)
toSum.inject{|sum, transaction_item| sum + transaction_item.amount}

See How to sum array of numbers in Ruby?

Community
  • 1
  • 1
Dennis Guse
  • 883
  • 10
  • 34
  • Hi Dennis. Could you explain a little bit more about whats going on with the transactions.each method? What should this be returning. I can't seem to get this to work in my rails console. Also, did you mean to put transaction"s"_items, or should it match the model, transaction_items? – Josh_Katz Jul 21 '13 at 16:51
  • @Josh_Katz added more explanation! – Dennis Guse Jul 22 '13 at 07:45
  • I got it! So the toSum is also an array, set equal to the records whose :amount equals 30. Then you loop through that array, adding the amount to the current sum? – Josh_Katz Jul 26 '13 at 05:02
  • @Josh_Katz toSum are the transactions_items you would like to sum up (amount => 30) and this array is then used to calculate the sum. – Dennis Guse Jul 26 '13 at 07:09