Is there any way to use ActiveRecord calculations while also acquiring relevant field names? For example, I’d like to find the average age of all people with the various last names. Basically I’d like to use:
Person.average(:age, :group_by => "last_name")
… as a substitute for
"Select last_name, AVG(age) FROM People GROUP BY last_name"
Any ideas?
This works pretty much exactly as you have described (though I think you’d use :group instead of :group_by) for single fields. The return is an OrderedHash, so the keys will be the last names and the values will be the average age for that last name.
Since any field that you return has to be included in the group, if you want to add additional fields, you can try doing something a little hackish. In Postgres, for example, you can concatenate the additional fields like so:
The keys in the return would be the comma separated first and last names. If you’re wanting ActiveRecord::Base objects returned, you have to resort to
"SELECT ..."style queries.