How to evaluate average product ratings using activerecord and POSTGRES

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.

+4
source share
2 answers

You can mix average and group to do something like

 MyClass.group('product_id').average('score') # => {product_id1 => average1, product_id2 => average2, ... } 
+6
source

You need to change the request as

 MyClass.select('product_id').group('product_id').average('score') 

look at the question .

Update:

Try MyClass.select('DISTINCT(product_id)').group('product_id').average('score')

See the group in postgres

+1
source

Source: https://habr.com/ru/post/1402020/


All Articles