newBike newBike - 1 month ago 5
Ruby Question

How to select data by monthly and weekly and quarterly

I have the an

Order
model in the following

If today is 5/3

and I want to sum the previous 3 months data of order, how to do it ?

I mean I want to show the
2/1 ~ 4/30
excluding the orders in May.

If today is 2014/4/20, and I want to show the sum of previous 3 weeks data.
2014/2/1~2/15


How to do it in Rubic way ?

Answer

You want something along the lines:

date = DateTime.now.utc
Order.where('created_at >= ? and created_at <= ?', date.beginning_of_month, date.utc.end_of_month).sum('price')

Where price is the column you want to sum.

You can reuse the logic of @Santosh in order to get the dates you want =)