I have a table where new records are added daily. How would I go about finding records created in the previous month?
Assuming your records are timestamped, you can just do something like this:
Thing.find(:all, :conditions => ["created_at > ?", Time.now - 1.month])
If they're not timestamped, you should start storing the information since it's something you'll want to look up later.
Set up a named scope:
named_scope :in_last_month, :conditions => [ "records.created_at > ?", 1.month.ago ]
To call it (in your controller):
Record.in_last_month
Thing.find(:all, :conditions => ["created_at > ?", 1.month.ago.at_beginning_of_month])
The named_scope
is a rather elegant way to go, I think, but if you take that route you will want to use it with a lambda
method so that the time doesn't get scoped to when the application is initially loaded.
For example, this:
named_scope :last_month, :conditions =>
['created_at > ? AND created_at < ?',
Date.today.last_month.beginning_of_month, Date.today.beginning_of_month]
will work properly the first month your application is up, but improperly the next month, unless the app gets restarted.
But this:
named_scope :last_month, lambda {
{:conditions => ['created_at > ? AND created_at < ?',
Date.today.last_month.beginning_of_month, Date.today.beginning_of_month]}}
will work every time, because the lambda method gets executed on every call, reevaluating the Date.today
s.
I don't have enough reputation to vote up yet, but please take note of the comment that mentions to use of lambdas in named_scopes. There's a Railscasts episode on the subject that should be useful as well: