开发者

How do I use .find for the last five days in ruby on rails?

开发者 https://www.devze.com 2022-12-30 00:19 出处:网络
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.

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号