I’m using the find method as follows:
@records = Effort.find( :all,
:select => 'full_name, taskType, sum(hours)',
:group => 'full_name, taskType',
...
@records.each do |record|
The query works fine. What I am confused about is how to access the sum(hours) value. I’ve tried the following:
record.sum(hours) # undefined local variable hours
record.sum_hours # sum_hours undefined
record[2] # Gives empty string
record[3] # Same, just double checking where the index might start...
I’m a bit stuck how to access the value! If I add <%= debug @records %> to my view, I see debugging output such as this:
---
- !ruby/object:Effort
attributes:
full_name: admin
taskType: Pre-Sales
sum(hours): '16'
What exactly are you trying to achieve with this query? Are you trying to get the sum of all
Effort‘s hours or group them by some other means?The query below
Will only ever return 1 value, because you’re selecting a
sum(hours)in there, which results in SQL aggregating the results into the first row. This means you’ll always get your firstEffortrow, with asum(hours)field set to the total amount of hours spent on all efforts.If you just want the sum of all
Efforthours, you can do this:Effort.sum(:hours)If you’re looking to sum hours based on some other criteria, please update your question.
EDIT
In this case you could do something like this,
@records = Effort.group(:full_name, :taskType).sum(:hours)You’ll end up with a hash that looks like this:
[full_name, taskType] => counti.e.
You could iterate over it like: