AlbertMunichMar
AlbertMunichMar

Reputation: 1896

ActiveRecord query with group and average

I have two models in a Rails application: a home has many speed_tests.

Every speed_test has as attributes: hostname and download.

I want to group hostnames and display the average of the download.

First of all I filter by city:

sts = SpeedTest.joins(:home).where("homes.city": city)

I have a collection of speed_tests, now I want to group them by hostname and get the average of download for every hostname

result = sts.select("hostname, AVG(download) as avg_download").group(:hostname)

The results are as following:

=> #<ActiveRecord::Relation [#<SpeedTest id: nil, hostname: "46.128.35.112.dynamic.cablesurf.de">]>

Why I can't see the column avg_download? Am I force to use the column speed_test id? I am not interested in this attribute.

Upvotes: 0

Views: 203

Answers (1)

Ursus
Ursus

Reputation: 30071

You can't see it because that field is not part of your model, it's a virtual attribute. Anyway, it's present. Just call it. Try

result.map(&:avg_download)

Upvotes: 1

Related Questions