Dave Olson
Dave Olson

Reputation: 252

select method not producing the right results in Rails 4

I have searched for hours trying to find a solution to this.

I am having problems with this statement. It returns nil but it should return a hash.

stats = stats.select("date, sum(attendance) as total_attendance")

I've run it in my console as:

Stat.select("date, sum(attendance) as total_attendance")

Here's the output from the console:

Stat.select("date, sum(attendance) as total_attendance")
  Stat Load (0.3ms)  SELECT date, sum(attendance) as total_attendance FROM "stats"
 => #<ActiveRecord::Relation [#<Stat id: nil, date: "2013-01-06">]>

The result I am looking for would be a hash with :date => value and :total_attendance => value like

attendance: 31, date: "2013-06-30"

I have also tried using

Stat.group(:date).sum(:attendance)

but it returns a hash with the date as the key and the total attendance as the value.

like so:

Sun, 06 Jan 2013=>66, Sun, 13 Jan 2013=>65

Can anyone tell me what I'm doing wrong? I thought the first statement would be correct, but the bottom line is I'm looking for the right result.

Upvotes: 1

Views: 441

Answers (1)

Konstantin Rudy
Konstantin Rudy

Reputation: 2257

The select statement expects several rows of results, whereas sum is a calculation and produces only one result for the entire table (if no where statement given). So sum should either be used together with group or directly on the class level:

Stat.sum(:attendance)

Update:

To get the hash you want just do:

Stat.select('date, sum(attendance) as total_attendance').group(:date)

If you don't group by date the result will be incorrect.

Upvotes: 1

Related Questions