0

那个标题不是很具描述性。我不知道如何缩短我的问题...

假设我有一个weightlifters包含namepounds、 和type_of_liftas 字段的表。该表中有数百个条目。我想检索表中总磅数最高的 10 人。我写了以下内容:

Weightlifter.order("pounds DESC").limit(10)

这工作正常,除了我想要累积权重。因此,如果一个人不止一次进入前 10 名,我不希望他的名字被列出两次,我想将权重加在一起并将它们显示为总和。所以如果我有:

"Johnny", "300", "Bench"
"Wesley", "295", "Bench"
"Johnny", "280", "Clean"
...
"Timmy", "150", "Curl"

我想显示 580 磅的约翰尼,而不是 300 磅的约翰尼,然后再显示 280 磅的约翰尼。

这是怎么做到的?

Ruby 1.9.3、Rails 3.2.6、SQLite3 3.6.20

谢谢!

4

2 回答 2

2

它应该是这样的

Weightlifter.select('name, type_of_lift, sum(pounds) as pounds').
             group('name').
             order("sum(pounds) DESC").
             limit(10)

这是一个很好的指南:ActiveRecord 查询接口

于 2012-07-27T23:36:16.510 回答
1
# in your WeightLifter model
class Weightlifter < ActiveRecord

  attr_accessor :weight_total


# WeightLifterController

lifters = []

Weightlifter.order("pounds DESC").each do |lifter| 

  return lifters if lifters.count == 10

  if !lifters.collect{|a| a[:name] }.include?(lifter.name)
    lifters << lifter
    local_lifter = lifters.where(name: lifter.name).first
    local_lifter.weight_total = lifter.weight
  else
    local_lifter = lifters.where(name: lifter.name).first
    local_lifter.weight_total = local_lifter.weight_total + lifter.weight
  end

end
于 2012-07-27T23:51:38.270 回答