Azzurrio
Azzurrio

Reputation: 1330

Select Range of records using created_at

I want to select a range of model records via created_at attribute, I tried this query

Client.where('created_at BETWEEN ? AND ?', 30.days.from_now, DateTime.now.utc)

But it return an empty array.

1.9.3-p125 :029 > Client.where('created_at BETWEEN ? AND ?', 30.days.from_now, DateTime.now.utc)
  Posting Load (1.0ms)  SELECT `clients`.* FROM `clients` WHERE (created_at BETWEEN '2012-09-22 16:30:04' AND '2012-08-23')
 => []

Also I want to group this records into array of arrays using .day method, I mean if I've 10 records I wanna group records which have created in the same day into separated array!

Upvotes: 1

Views: 1665

Answers (2)

Caleb Hearth
Caleb Hearth

Reputation: 3365

Client.
  where(created_at: 30.days.ago..Date.current).
  group_by{|u| u.created_at.to_date}

You can pass where an array of values between which you would like the results (for inclusive vs. exclusive ranges, look up the differences between .. and ...).

Further, you can group results by calling group_by, which will take a method to call, i.e. .group_by(&:created_at) or a block, as in my example. I used a full block because you wanted the results grouped by date rather than by specific timestamp. If you actually want the day of the month rather than the full date, you can also call .group_by{ |u| u.created_at.day}, but the date seems more useful to me.

Upvotes: 5

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

I believe what you want is (note ago versus from now):

Client.where('created_at BETWEEN ? AND ?', 30.days.ago.utc, Time.now.utc)

Upvotes: 2

Related Questions