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.f开发者_C百科ind(:conditions=> ???)
But not clear what exactly is the best way. Thanks!
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
ContactEmail.find(:conditions => ['date_sent BETWEEN ? AND ?', Date.today, 5.day.ago.to_date])
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)
精彩评论