简体   繁体   中英

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.

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!

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.

def todays_tasks(day)
   Task.where(:created_at => day.beginning_of_day .. day.end_of_day)
end

Wouldn't it be:

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

Or else you would never check for 00:00:00 on the day of the tasks and 11:59:59 is the last value at the end of the day of tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM