Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Find tasks that were created on a certain day?

I have a list of tasks (name, starts_at) and I'm trying to display them in a daily view (just like iCal).

def todays_tasks(day)
    Task.find(:all, :conditions => ["starts_at between ? and ?", day.beginning, day.ending]
end

I can't figure out how to convert Time.now such as "2009-04-12 10:00:00" into the beginning (and end) of the day dynamically so I can make the comparison.

like image 851
kush Avatar asked Apr 12 '09 19:04

kush


2 Answers

def todays_tasks(now = Time.now)
  Task.find(:all, :conditions => ["starts_at > ? AND < ?", now.at_beginning_of_day, now.at_end_of_day])
end

Voila!

like image 137
August Lilleaas Avatar answered Oct 26 '22 10:10

August Lilleaas


Expanding on augustl's answer a little bit. In your Task model you could define a method to fetch these tasks for you.

  def self.todays_tasks(t = Time.now)
    Task.all(:conditions => ["created_at > ? AND created_at < ?", t.at_beginning_of_day, t.tomorrow.at_beginning_of_day])
  end

This helps keep your controller skinny. I also compare the end of the day to the beginning of tomorrow. This makes sure that if a user creates a task at 11:59:59 PM it remains in the correct day.

like image 45
vrish88 Avatar answered Oct 26 '22 08:10

vrish88