orrymr
orrymr

Reputation: 2493

Grouping by a column using ActiveRecord

I've got the following model in RoR:

rails g model MyTable col1:string col2:integer

I then added the following data to it:

col1|col2 
a__ |7__ 
a__ |3__ 
b__ |5__ 
b__ |2__ 

I want to group by col1 and get the sum of col2 for each group. I did the following:

data = MyTable.all
data2 = data.select("col1, SUM(col2) as col2_all").group("col1")

The second line gives the following SQL:

SELECT col1, SUM(col2) as col2_all FROM "my_tables" GROUP BY "my_tables"."col1"

But the output I get doesn't look right:

<ActiveRecord::Relation [#<MyTable id: nil, col1: "a">, #<MyTable id: nil, col1: "b">]>

I don't seem to get col2_all as I expected.

What am I doing wrong?

Upvotes: 1

Views: 65

Answers (2)

Mike Desjardins
Mike Desjardins

Reputation: 460

I'm pretty sure that, if col2_all isn't an attribute of your MyTable model, you're not going to see it.

Does this work?

MyModel.group(:col1).sum(:col2)

Upvotes: 1

Adeptus
Adeptus

Reputation: 683

MyTable.group(:col1).sum(:col2)

Upvotes: 3

Related Questions