开发者

What does Rails ActiveRecord find return

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

@records = Effort.find( :all,
                        :select => 'full_name, taskType, sum(hours)',
                        ...

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 first Effort row, with a sum(hours) field set to the total amount of hours spent on all efforts.

If you just want the sum of all Effort hours, 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] => count

i.e.

['baking cookies', 'baking'] => 12
['baking cakes', 'baking'] => 2
...

You could iterate over it like:

@records.each do | (full_name, task_type), hours |
  puts 'Full Name: #{full_name}, Task Type: #{task_type}, Total Hours: #{hours}'
end


While looking back at my post and the debug output, it suddenly occurred to me it is right there on the page:

record.attributes[ 'sum(hours)' ]

I suppose that stuff like record.full_name is really a convenience method for accessing the attributes array?


not sure if it works, but you might want to try this :

@sums = Effort.sum(:hours, 
                   :group => [:project_task_id, :user_id],
                   :joins => [:project_task, :user])

it should give you an array of records. You should then normally be able to collect these:

@array = @sums.collect do |aggregate|
           [aggregate.project_task.name, aggregate.user.name, aggregate.hours]
         end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜