Rails Dates Time and Fixtures

standup75 picture standup75 · Dec 3, 2010 · Viewed 9.9k times · Source

I had the following fixture:

link_1:
  user: tom
  image: boy1
  created_at: <%= 5.day.ago %>

I tried the following request:

Links.where("Date(created_at) = ?", 5.day.ago.to_date)

Answer:

[]

grrrr....typing...typing...scratching... I finally tried:

link_1:
  user: tom
  image: boy1
  created_at: <%= 5.day.ago.to_date %>

and

Links.where("Date(created_at) = ?", 5.day.ago.to_date)

finally answers

[#<Link id: 298486374, user_id: 1038054164, image_id: 482586125, created_at: "2010-11-28 00:00:00", updated_at: "2010-12-03 21:32:19">]

What I was expecting, but why did I need to put to_date? It is not clear to me, because when I create an object without specifying the creation date, I can select them with the following where clause without issue:

Links.where("Date(created_at) = ?", Date.today)

Any idea?

Answer

lbz picture lbz · Dec 3, 2010

In fixtures you should have:

created_at: <%= 5.day.ago.to_s(:db) %>

Your query will be a:

Links.where("created_at = ?", ...

Let ActiveRecord taking care of the details about moving data from and to the database. We are using an ORM for a reason.

Reference.