Reputation: 1758
My DB columns for model Taxline: ID, RECEIPT, TAXID, BASE, AMOUNT
Let say I have db entries:
1,1,001,30$,3$
2,1,001,50$,5$
3,2,001,20$,2$
I want to show sum of amount for each receipt. Result should be:
1,8$
2,2$
My controller
class TaxlinesController < ApplicationController
def index
@taxlines = Taxline.group(:RECEIPT).sum(:AMOUNT)
end
end
My View:
<% @taxlines.each do |taxline| %>
<td><%= taxline.RECEIPT %></td>
<td><%= taxline.AMOUNT %></td>
But I get error undefined method `RECEIPT' for ["01a8fdd7-8eb6-44d0-a686-8010b9e30206", 145000.0]:Array
145000.0 and 01a8fdd7-8eb6-44d0-a686-8010b9e30206 refer to real vaules in db not to the example above. But it gives the idea.
App is built on existing db with column names uppercase.
What am I doing wrong?
Upvotes: 1
Views: 1192
Reputation: 12643
Your problem is that Taxline.group(:RECEIPT).sum(:AMOUNT)
returns a Hash object rather than a set of Taxline instances like you are expecting. They keys are the grouped values (RECEIPT) and the values are the corresponding sums. Something like:
{ "01a8fdd7-8eb6-44d0-a686-8010b9e30206" => 145000.0, ... }
When you do @taxlines.each
the Hash gets coerced into an Array.
With your current code you could simply change your view to this:
<% @taxlines.each do |receipt, amount| %>
<td><%= receipt %></td>
<td><%= amount %></td>
Upvotes: 1