views:

366

answers:

8

I have a table where new records are added daily. How would I go about finding records created in the previous month?

A: 

Do you have the "usual" fields on your table? See the RoR wiki for a list of them. That way, you can express special queries to find an answer.

Keltia
+2  A: 

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.

Chuck
Alternatively you can do 1.month.ago which is the same thing as Time.now - 1.month.
Ryan Bigg
+6  A: 

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
Andrew Vit
You might want to add that you need to add a created_at column, otherwise Rails won't auto-populate it for you.
Otto
The created_at should be included in a default migration which adds "timestamps" automatically. Also note that what I showed here for the named_scope should be enclosed in a lambda as someone nicely noted below...
Andrew Vit
A: 
Thing.find(:all, :conditions => ["created_at > ?", 1.month.ago.at_beginning_of_month])
August Lilleaas
+1  A: 

Thanks everyone, I ended up going with this:

find(:all, :conditions => ['created_at > ? AND created_at < ?', Date.today.last_month.beginning_of_month, Date.today.beginning_of_month])
+2  A: 

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.todays.

Ian Terrell
A: 

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:

http://railscasts.com/episodes/108

trevorturk
A: 

this is a good candidate for SQL's BETWEEN syntax

named_scope :last_month, :conditions => ['created_at BETWEEN ? AND ?', Date.today.last_month.beginning_of_month, Date.today.beginning_of_month])