Let's 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 present the average score for each product... So is there a way to query the DB using Rails to do this? I'm sure there must be, but I can't figure it out. I would like the following to occur:
Toyota Corolla 70%
Toyota Camry 78%
Toyota Avalon 80%
.. obviously based on multiple reviews for each that are averaged, but presented in the above fashion.
UPDATE:
For those interested in the 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 the view:
<% @reviews.each do |review| %>
<%= review.aidmodel.id %>
<%= @ordered_hash[review.aidmodel_id] %>
<% end %>
The @ordered_hash[review.aidmodel_id]
line provides the averaged score for the aidmodel with the desired ID.
You can mix average and group to do something like
MyClass.group('product_id').average('score')
# => {product_id1 => average1, product_id2 => average2, ... }
You need to change the query as
MyClass.select('product_id').group('product_id').average('score')
have a look at the question.
Update:
Try MyClass.select('DISTINCT(product_id)').group('product_id').average('score')
Look here group by in postgres
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With