Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Dates Time and Fixtures

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?

like image 458
standup75 Avatar asked Dec 03 '10 21:12

standup75


People also ask

What are rails fixtures?

Fixtures are data that you can feed into your unit testing. They are automatically created whenever rails generates the corresponding tests for your controllers and models. They are only used for your tests and cannot actually be accessed when running the application.

What exactly are harnesses and fixtures in the Ruby?

14) What exactly are Harnesses and Fixtures in the Ruby? These are basically the supporting codes with the help of which the users can easily write and can run the test cases. With the help of a rake, the users can then simply proceed with the automated tests.

What are RSpec fixtures?

Fixtures allow you to define a large set of sample data ahead of time and store them as YAML files inside your spec directory, inside another directory called fixtures. When you're test sweep first starts up RSpec will use those fixture files to prepopulate your database tables.


2 Answers

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.

like image 78
lbz Avatar answered Oct 13 '22 10:10

lbz


I would speculate that it's because of the time difference between when the fixture was created and when the query was called.

5 days ago + 0.00025 ms > 5 days ago

I'm not sure what the precision is for datetimes, but it's the only possibility I can think of. When you converted it to a date, your removed the extraneous time information and rendered the two equal.

like image 36
Chuck Callebs Avatar answered Oct 13 '22 09:10

Chuck Callebs