This project is archived and is in readonly mode.

#497 ✓committed
gix

ActiveRecord#calculate broken for multiple fields in :group option

Reported by gix | June 27th, 2008 @ 03:45 AM | in 3.0.5

The docs to ActiveRecord#calculate state:

:group - An attribute name by which the result should

be grouped. Uses the GROUP BY SQL-clause.

Most likely to be compatible to finders. But this statement is only partially true. The method's algorithm assumes that :group contains only one field. When specifying multiple values -- e.g. :group => 'foo, bar' -- this does not work anymore.

If one were to use ActiveRecord#count to get only the size of a result set (as the will_paginate-plugin does for example) this used to work in Rails 2.0 and was broken by http://preview.tinyurl.com/3l77f7 [Rails-Changeset]. Now the final result array with grouped key => aggregated value pairs is totally broken because keys are overwritten:

>> Item.count(:group => 'item_id').size

=> 687

>> Item.count(:group => 'quality').size

=> 2

>> Item.count(:group => 'item_id, quality').size

=> 2 # item_id is primary key, should return 687

>> Item.count(:group => 'quality')

=> [[5, 2], [4, 685]]

>> Item.count(:group => 'item_id, quality')

=> [[4, 1], [5, 1]]

I do not know how this should or can be fixed. Ideally every field in :group should be taken into account and used as some sort of combined key. The major problem I see here is splitting the :group string into fields because a simple split(/\s*,\s*/) won't work for more advanced things like 'COALESCE(col1, col2)'.

Another solution would be to allow :group being an array, thus putting the splitting in the hands of the caller:

Model.calculate(:op, :group => ['c', 'COALESCE(c1, c2)'])

This should be changed for finders as well then.

Otherwise the docs should be changed to reflect that multiple fields are not possible.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages