0

Building a Task Manager and need help limiting my Task model to only tasks that are due today I've tried comparing my task's duedate to Date.now but doesn't seem to be working.

This is my schema

  create_table "tasks", force: :cascade do |t|
    t.string "title"
    t.string "description"
    t.datetime "duedate"
    t.boolean "completed"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

This is my Task model.

class Task < ApplicationRecord
  #use scope on Task model to mark overdue Tasks if the present date is greater than duedate.
  scope :overdue, -> { where("duedate < ?", Time.now) }
  scope :due_today, ->{ where("duedate = ?", Date.now) }

  def overdue?
    duedate < Time.now
  end

  def due_today?
    duedate = Date.now
  end
end


Joshua
  • 13
  • 4
  • Nope. It doesn't. I keep getting a NoMethodError (undefined method `now' for Date:Class) – Joshua May 18 '21 at 00:50
  • Yes, Date doesn't have a now method. It has a today method. The first answer to that question shows how to do a "is this timestamp on this day" using a range. – Schwern May 18 '21 at 00:55
  • I've tried that in my controller using. ``` def due_today @tasks = Task.all.where(:duedate = Date.now.beginning_of_day..Date.now.end_of_day) end ``` – Joshua May 18 '21 at 00:56
  • Note that Date.today should be avoided in Rails because of time zones. Use the Date.current Rails extension. https://thoughtbot.com/blog/its-about-time-zones – Schwern May 18 '21 at 00:57
  • def due_today @tasks = Task.all.where(:duedate = Date.current.beginning_of_day..Date.current.end_of_day) end – Joshua May 18 '21 at 01:00
  • that didn't work either. – Joshua May 18 '21 at 01:00
  • It's `:duedate =>` or `duedate:`, not `:duedate =`. Like a Hash. And they are class methods on Date. `scope :due_today, ->{ where(due_date: Date.beginning_of_day..Date.end_of_day) }`. See Rails extensions to [Time](https://api.rubyonrails.org/classes/Time.html) and [Date](https://api.rubyonrails.org/classes/Date.html). – Schwern May 18 '21 at 01:03
  • got this when I used that class method NoMethodError (undefined method `beginning_of_day' for Date:Class) Did you mean? beginning_of_week – Joshua May 18 '21 at 01:11
  • This worked! scope :due_today, ->{ where("duedate >= ? AND duedate <= ?", Date.current.beginning_of_day, Date.current.end_of_day) } – Joshua May 18 '21 at 01:14

0 Answers0