Reputation: 2804
I've looked around and can't see any reason why my Date.yesterday query isn't working.
I have this in my model:
scope :yesterday, lambda {
where('acctstarttime = ?', Time.now - 1.day)
}
And I've tried
scope :yesterday, lambda {
where('acctstarttime = ?', (Time.now - 1.day).strftime('%Y-%m-%d'))
}
And...
scope :yesterday, lambda {
where('acctstarttime = ?', Date.yesterday)
}
I get a result like this:
Radacct.yesterday.count
(440.1ms) SELECT COUNT(*) FROM `radacct` WHERE (acctstarttime like '2013-01-27 22:55:31')
(I've also tried Date.yesterday)
Where as using today yields:
Radacct.today.count
SELECT COUNT(*) FROM `radacct` WHERE (acctstarttime >= '2013-01-28')
=> 16,456
If I modify the look up as follows it works:
Radacct.find(:all, :conditions => ["acctstarttime like ?", (Date.today-1).strftime('%Y-%m-%d')+ "%"]).count
Am I just tired or is this overly complicated? What's the best and shortest way in Rails 3 to achieve this? It seems to get stuck with the time aspect..
Upvotes: 0
Views: 42
Reputation: 6808
Notice the '>=' on today
. The problem is that you are testing equality with yesterday, when what you really want to test is a range. Try this:
scope :yesterday, lambda {
where(:acctstarttime => Date.yesterday.beginning_of_day..Date.yesterday.end_of_day)
}
Or
scope :yesterday, lambda {
where('acctstarttime >= ? && acctstarttime <= ?', Date.yesterday, Date.today)
}
Upvotes: 2