0

I have a Rails app which uses Postgresql.

Please check out the following command and its output from Rails console:

[11] pry(main)> User.last.created_at_before_type_cast
  User Load (0.6ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> "2018-08-29 11:10:46.526069"

What does the number 526069 represent and how it gets generated?

2 Answers 2

4

Postgres stores timestamps with timezones internally using UTC, however before displaying ActiveRecord will serialize/typecast to your application's timezone.

pry(main)>d = DateTime.now.in_time_zone("Asia/Kolkata") => Sat, 07 Oct 2017 00:38:26 IST +05:30 pry(main)> Booking.where('created_at > ?', d).count (1.4ms) SELECT COUNT(*) FROM "bookings" WHERE (created_at > '2017-10-06 19:08:40.011480')

As you can see, d was converted to UTC to perform the search in the postgres database.
The created_at_before_type_cast method will return the value of created_at exactly how it's stored in the database without serializing/typecasting based on your ActiveRecord configuration.

As bkimble already pointed out: The numbers at the end are milliseconds.

You should have a look at the following for a deeper understanding:

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

Comments

2

That represents microseconds. See https://ruby-doc.org/core-2.2.2/Time.html . By default, all Time has microseconds. Check it out yourself by casting Time.now to float:

Time.now.to_f
= > 1535595572.4089978

If you want to drop the microseconds, cast it to int:

Time.now.to_i
=> 1535595649

I'd imagine a field like 'created_at_before_type_cast' represents the Time before it gets cast to an integer.

2 Comments

Why would it get cast to an integer if the column is a date type?
That's just speculation on my part. It sounds like you're surprised at the microtime showing up. Depending on your database type and column type, it could be storing it in microtime and all you'd ever get is microtime out of it (unless you casted it to_i yourself)

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.