1

Can anyone please explain me, why my db queries return empty, when I have data in my table?

Event.all

returns

...
Event Load (0.3ms)  SELECT "events".* FROM "events"
 => #<ActiveRecord::Relation [#<Event id: 1, created_at: "2013-08-01 12:27:36", updated_at: "2013-08-01 12:27:36"> 
...

etc,

While

Event.where(created_at: Date.today)

gives me

Event Load (0.3ms)  SELECT "events".* FROM "events" WHERE "events"."created_at" = '2013-08-01'
 => #<ActiveRecord::Relation []> 

Where is everything?

1
  • 1
    What DBM are you using? Typically we'd truncate the DateTime value to a date in the query to make it match. Commented Aug 1, 2013 at 14:04

3 Answers 3

3

The field created_at is a DateTime, but you are comparing it to a Date (no time). You need to Cast the field as a Date to get all Events created today:

Event.where('CAST(events.created_at as DATE) = ?', Date.today)

Attention: The syntax may change depending on your Data-base system (PostGreSQL / MySQL, etc).

Hope this helps!

Useful link:

Sign up to request clarification or add additional context in comments.

Comments

0

If you look at your actual query -

SELECT "events".* FROM "events" WHERE "events"."created_at" = '2013-08-01'

You are looking for a record with created_at equals 2013-08-01, but in actuality, the record you are trying to search for - the created_at field equals 2013-08-01 12:27:36.

Change your statement to do a search for created_at that contains 2013-08-01

Comments

0

The problem is that the created_at: attribute (assuming that it was created in the migration timestamps) also stores the time. So it will never equal a simple date. You're best option is to parse the date and then compare it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.