Skip to content

Instantly share code, notes, and snippets.

Last active January 6, 2018 22:27
What would you like to do?
Add missing timestamps to previously existing tables in Rails
## rails g migration add_timestamps
## Insert the following, with whatever version of ActiveRecord you're using.
class AddTimestamps < ActiveRecord::Migration[5.0]
def change
ActiveRecord::Base.connection.tables.each do |table_name|
columns = ActiveRecord::Base.connection.columns(table_name).map { |c| }
["created_at", "updated_at"].each do |timestamp|
unless columns.include?(timestamp)
add_column table_name, timestamp, :datetime
## rake db:migrate
Copy link

JonathanWThom commented Jan 6, 2018

Note to anyone looking - this does not include the null: false option. I found that running it with that threw errors on the schema_migrations column. You may not even want schema_migrations to have timestamps, so feel free to skip that in the script if you want to include the null option. And if anyone knows why it behaves that way, I'm all ears!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment