Rails Active Record连接查询

时间:2013-02-28 11:15:05

标签: ruby-on-rails-3 activerecord

帮我解决下一个问题:

我有表brands和表productshas_many - belongs_to association

在表格产品中,我有字段“Rank”。

我想展示其产品总排名前5位的前五大品牌

我试着:

Brand.joins(:products).order('products.rank DESC').limit(10).uniq!

但那不正确 - 那不是产品的总和。然后......

如何使用产品等级的总和来实现

1 个答案:

答案 0 :(得分:1)

你很接近,但是你错过了对分组对象进行分组和执行总和的过程:

Brand.joins(:products).group("brands.id").order('SUM(products.rank) DESC').limit(5)
相关问题