Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to average product review scores using activerecord and POSTGRES

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.

like image 631
Abram Avatar asked Feb 21 '23 02:02

Abram


2 Answers

You can mix average and group to do something like

MyClass.group('product_id').average('score')
# => {product_id1 => average1, product_id2 => average2, ... }
like image 84
Baldrick Avatar answered May 08 '23 10:05

Baldrick


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

like image 41
asitmoharna Avatar answered May 08 '23 10:05

asitmoharna