如何使用ActiveRecord和POSTGRES平均产品评论评分 [英] How to average product review scores using activerecord and POSTGRES

查看:99
本文介绍了如何使用ActiveRecord和POSTGRES平均产品评论评分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张桌子,上面有100条商品评论。每个评论都有一个 id, product_id和 score。现在,我想做的是呈现每种产品的平均得分...那么有没有办法使用Rails来查询数据库呢?我确定一定有,但我无法弄清楚。我希望发生以下情况:

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.

更新:

对于那些对解决方案感兴趣的人

For those interested in the solution

这是在控制器中:

@ordered_hash = Review.group('aidmodel_id').average('score')
@keys = @ordered_hash.keys
@reviews = Review.where(:aidmodel_id=>@keys).uniq_by {|x| x.aidmodel_id}

在视图中:

<% @reviews.each do |review| %>

    <%= review.aidmodel.id %>
    <%= @ordered_hash[review.aidmodel_id] %>

  <% end %>

@ordered_hash [review.aidmodel_id]

推荐答案

您可以混合使用平均值 group 做类似的事情

You can mix average and group to do something like

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

这篇关于如何使用ActiveRecord和POSTGRES平均产品评论评分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆