views:

70

answers:

3

Have a model called contact_email.date_sent

I want to be able to run a report which displays all those where the date_sent range is between date.today and date.today 5 days ago.

I assume I use something like

@send_emails = Contact_Email.find(:conditions=> ???)

But not clear what exactly is the best way. Thanks!

+1  A: 

ContactEmail.find(:conditions => ['date_sent BETWEEN ? AND ?', Date.today, 5.day.ago.to_date])

Eimantas
You could also just use >, since presumably your database does not contain emails from the future.
bnaul
Correct, but this condition helps finding stuff in retrospective.
Eimantas
+1  A: 

Try this:

ContactEmail.all(:conditions => ["date_sent >= ?", 5.days.ago.to_date])

This approach is faster than using BETWEEN clause( assuming date_sent is indexed)

Caveat:

Value of date_sent column should be less than current date.

Edit 1

To add an index in migration:

add_index :contact_emails, :date_sent
KandadaBoggu
Is it possible to make it so that I can get what has been sent Monday through Friday of the week that Date.today is?
Angela
HOw do I create a migration to add date_sent as an index (date_sent alrady exists, but wasn't set as index)?
Angela
Updated the answer, take a look.
KandadaBoggu
thanks perfect.
Angela
Hi, there, I have another question, I was wondering if you could help me...are you familiar with Single Table INheritances?
Angela
What is the question?
KandadaBoggu
A: 

If it's something you will use regularly, why not put a named_scope in the model:

named_scope :recent, lambda { |*args| {:conditions => ["date_sent > ?", (args.first || 5.days.ago)]} }

which will let you write:

ContactEmail.recent

for the last 5 days worth, or use the arg to specify your own time frame e.g. the last two weeks:

ContactEmail.recent(2.weeks.ago)
par
I liked this idea...I need to brush up on named_scope though...
Angela