Add missing timestamps to previously existing tables in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to anyone looking - this does not include the
null: false
option. I found that running it with that threw errors on theschema_migrations
column. You may not even wantschema_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!