DateTime, Timestamp, Time and Date in Rails

Learn about key differenece between DateTime, Timestamp, Time and Date in Rails
31 October 2017   602

The difference between different date/time formats in ActiveRecord have little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATEDATETIMETIME and TIMESTAMP column data types; just as you have CHARVARCHARFLOATand INTEGER.

So, main differences: DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIMEstores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

How to redirect to 404 page in Rails?

Small tutorial that will help you to redirect user to a "fake" 404 page, using Rails
31 October 2017   464

Rails has this functionality built in already. If you want to show a 404 page, create a render_404 method (or not_found ) in ApplicationController like this:

def not_found
  raise'Not Found')

Rails also handles AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.

This does two things better:

It uses Rails' built in rescue_from handler to render the 404 page, and 2) it interrupts the execution of your code, letting you do nice things like:

  user = User.find_by_email(params[:email]) or not_found

without having to write ugly conditional statements.

As a bonus, it's also super easy to handle in tests.