开发者

Finding entries belonging to current month (or other months)

I have a model (Expense) that contains fields like 'cost'.

I'd like to iterate through all my expenses to find the sum of the co开发者_JAVA技巧st for all entries belonging to a particular month.

Is there a way to do it in rails directly?

Expense.find(:all, :conditions => .....)


To get the SUM of costs for the month of a given date:

  # date = any day of the month of intrest
  Expense.sum(:cost, :conditions => {:created_at => 
              (date.beginning_of_month..date.end_of_month)})

To get the sum of costs of all the months:

Expense.sum(:cost, 
    :group => "EXTRACT(YEAR_MONTH FROM created_at)").each do |y_m, cost_sum|
  p "#{y_m}-#{cost_sum}"
end

In the above call, use the conditions option to restrict the result-set to a date range.


sum/group_by:

Expense.find(:all, 
             :select => "SUM(cost) as cost_sum, MONTH(date) as month, YEAR(date) as year",
             :group => "MONTH(date), YEAR(date)" )


Have a look at this beautiful gem: https://github.com/radar/by_star

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜