Skip to content

Instantly share code, notes, and snippets.

@m5rk
Created September 16, 2014 14:24
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 m5rk/4b5e47eed1da5510c1ab to your computer and use it in GitHub Desktop.
Save m5rk/4b5e47eed1da5510c1ab to your computer and use it in GitHub Desktop.
Migration to update timestamps to null: false
# Rails 3.2 generated timestamps with null: false but then this was reverted before 4.0
# so if you migrated from 3.2 to 4.x, you'll always have this perpetual skew between your
# schema in source control and the schema in the database unless you correct it like
# this:
class SetTimestampsToNotNull < ActiveRecord::Migration
def change
tables = ActiveRecord::Base.connection.tables - ["schema_migrations"]
tables_with_timestamps = tables.select do |table|
ActiveRecord::Base.connection.columns(table).map(&:name).include?('created_at')
end
tables_with_timestamps.each do |table|
change_column table.to_sym, :created_at, :datetime, null: false
change_column table.to_sym, :updated_at, :datetime, null: false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment