Sum column values under condition
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)
精彩评论