开发者

Rails 3 - How to use filter results of sum operation?

开发者 https://www.devze.com 2023-01-16 05:12 出处:网络
I am working on a Rails 3 app, and I need to return back a list of players where the sum of points_received per player, is greater than a specified amount.

I am working on a Rails 3 app, and I need to return back a list of players where the sum of points_received per player, is greater than a specified amount.

I have tried this:

Answer.sum(:points_received, :group => 'player_id').having("points_received > 5")

but of course this gives me an error: NoMethodError: undefined method `having' for #

Answer model is defined as:

 create_table "answers", :force => true do |t|
    t.integer  "player_id"
    t.integer  "round_id"
    t.string   "response"
    t.integer  "points_received"
  end

So I understand that sum is returning back an ordered hash of player_id, sum(points_received), but I only want to see the results where the sum(points_received) is greater than a specified value.

Any suggestions?

Thanks in a开发者_如何学Cdvance!


Can you believe it, just after I posted this, I then had a thought on swapping some syntax around and got the result. This is what I ended up doing:

Answer.group(:player_id).having("sum(points_received) > 5").sum(:points_received)

this returned me back the hash of player_ids and sum(points_received) for only the ones where the sum is greater than 5.

Thanks for reading anyway. Maybe this will help someone one day!

0

精彩评论

暂无评论...
验证码 换一张
取 消