开发者

Sum column values under condition

开发者 https://www.devze.com 2023-03-22 11:43 出处:网络
Suppose this: Works table Name created_at Size I want to list all works and in the end sum up all Size values, but under one condition. created_at must be < 1 year ago.

Suppose this:

Works table

Name
created_at
Size

I want to list all works and in the end sum up all Size values, but under one condition. created_at must be < 1 year ago.

I know

@works.sum(&:size)

works but it doesn't filter out the 'cre开发者_开发问答ated_at' part.

Then i got to this @works.sum(&:size, :conditions => ['created_at > ?', 1.year.ago])

But keep getting a compile error about expecting a ) instead of a ,

Help please? Any better way to accomplish this?


you can use scope to keep the model clean

#controller
class WorksController < ApplicationsController

  def index
    @works.recent.sum(&:size)
  end
end

#model
class Work
 scope :recent, ->{ where('created_at > ?', 1.year.ago) }
end


This worked for me:

@works.where('created_at > ?', 1_year_ago).sum(:size)
0

精彩评论

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