maclover7
maclover7

Reputation: 137

Check if a datetime field is equal to Date.today

I'm trying to check if an assignment's due_date (datetime data type) is equal to Date.today. The logic I need help with is the 'due_date: Date.today' section. Thanks in advance.

@student_assignments = StudentAssignment.joins(:assignment).where(assignments: { due_date: Date.today })

Upvotes: 2

Views: 1780

Answers (3)

max
max

Reputation: 101821

To compare with a datetime column you need to have a DateTime object. However if you compare a for equity with DateTime.now.beginning_of_day it will only match assignments with are due at 00:00.

Instead if you want assigments that are due today you could do:

StudentAssignment.joins(:assignment)
         .where(assignments: { 
            due_date: DateTime.now.beginning_of_day..DateTime.now.end_of_day 
         })

You can create a named scope:

class Assignment < ActiveRecord::Base 
  scope(:due_today) -> {
    where(due_date:DateTime.now.beginning_of_day..DateTime.now.end_of_day )
  }
end

Upvotes: 0

zwippie
zwippie

Reputation: 15515

.where("DATE(assignments.due_date) = ?", Date.today)

Upvotes: 2

jazzytomato
jazzytomato

Reputation: 7214

Here is a possible solution :

{ due_date: (Date.today.beginning_of_day..Date.today.end_of_day) }

Upvotes: 0

Related Questions