image by Roman Bozhko

Use Rails’ naming conventions for dates & times

Rails includes the default managed timestamps updated_at and created_at for ActiveRecord models.

RailsConf 2024

I'm co-chairing RailsConf 2024 in Detroit May 7–9. Come and join us 

However, on many applications, diving into a schema.rb or migration often reveals something_date as a field name on a model.

Instead of…

…including the words date or time in your database columns:

class NaughtyMigration < ActiveRecord::Migration[5.1]
  add_column :users, :logged_in_date, :datetime
  add_column :users, :logged_out_time, :date


…the suffix at for times and on for dates.

class AwesomeMigration < ActiveRecord::Migration[5.1]
  add_column :users, :logged_in_at, :datetime
  add_column :users, :logged_out_on, :date

But why?

Including the word time or date in the variable name is redundant and adds to the visual noise of the code. You don’t say first_name_string, do you?

Given Rails’ conventions, something like a due_on field lets you know to expect a date. You give instant feedback to anyone reading your code about the expected data stored in the database.

I might allow myself the occasional _until if it makes the variable easier to read.

For me, the naming constraint also makes me think harder about the right name.

Brighton Ruby 2024

Still running UK’s friendliest, Ruby event on Friday 28th June. Ice cream + Ruby 

Last updated on September 29th, 2017 by @andycroll

An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.