2012-03-06 68 views
0

我已經在我的'StatementSales'模型中編寫了以下總和/方法,並希望能夠按日期約束結果,此時它只是生成所有有效數據庫條目的總計。在我看來,我想提供「一週,一個月,三個月,一年」等鏈接,理想情況下將它們傳遞給下面的方法。我應該如何處理這個問題?帶日期約束的求和/分組?

def self.total_units 
sum(:units) 
end 

def self.units_by_store 
group(:store).sum(:units) 
end 

def self.units_by_territory 
group(:territory).sum(:units) 
end 

def self.units_by_upc 
group(:upc).sum(:units) 
end 

非常感謝提前!

回答

0

你可以使用範圍

添加到您的類

scope :between_dates, lambda { |start_date, end_date| where("date < #{end_date} AND date >= #{start_date}") } 
scope :one_week, between_dates(Date.today, Date.today + 7.days) 

然後,你可以做

def self.total_units 
    self.one_week.sum(:units) 
end 
+0

謝謝!只是給了這個嘗試,但似乎我從SQLite表中得到一些奇怪的日期(例如格式爲2455958.5日期),因此沒有結果。我確實在數據庫中直接輸入了一些虛擬數據,但是在其他表中,通過UI添加或導入它們看起來不錯? – Raoot 2012-03-06 12:49:23