Say I have a table with 100 product reviews. Each review has an id, product_id, and score. Now, what I want to do is the average score for each product ... So is there a way to query the database using Rails for this? I'm sure it should be, but I can't figure it out. I would like the following:
Toyota Corolla 70% Toyota Camry 78% Toyota Avalon 80%
.. obviously, based on a few reviews for each, which are averaged but presented above.
UPDATE:
For those who are interested in a solution
This is in the controller:
@ordered_hash = Review.group('aidmodel_id').average('score') @keys = @ordered_hash.keys @reviews = Review.where(:aidmodel_id=>@keys).uniq_by {|x| x.aidmodel_id}
This is in view:
<% @reviews.each do |review| %> <%= review.aidmodel.id %> <%= @ordered_hash[review.aidmodel_id] %> <% end %>
The line @ordered_hash[review.aidmodel_id] provides an average score for the reference model with the desired identifier.
Abram source share