Skip to content

Instantly share code, notes, and snippets.

@JonathanWThom
Last active January 6, 2018 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanWThom/7e3b4218be335f2b9b40012c435b90be to your computer and use it in GitHub Desktop.
Save JonathanWThom/7e3b4218be335f2b9b40012c435b90be to your computer and use it in GitHub Desktop.
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| c.name }
["created_at", "updated_at"].each do |timestamp|
unless columns.include?(timestamp)
add_column table_name, timestamp, :datetime
end
end
end
end
end
## rake db:migrate
@JonathanWThom
Copy link
Author

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