Created
April 20, 2019 16:24
-
-
Save awesome/e8200c9b2836134fe793dc11911788bb to your computer and use it in GitHub Desktop.
script generate migration remove foreign key constraints; cut and paste in up/down/change block rails; uses schema_plus_foreign_key "4-argument" syntax https://github.com/SchemaPlus/schema_plus_foreign_keys/blob/affa91c1a508dae2ff8bb7be9e3ed4731106ae1e/lib/schema_plus/foreign_keys/active_record/connection_adapters/abstract_adapter.rb#L31
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
sql = "SELECT | |
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME | |
FROM | |
INFORMATION_SCHEMA.KEY_COLUMN_USAGE | |
WHERE REFERENCED_TABLE_SCHEMA = 'awesome_db'" | |
x = ActiveRecord::Base.connection.execute(sql) | |
# remove constraints | |
z = x.map {|y| | |
"remove_foreign_key :#{y[0]}, column: '#{y[1]}', name: '#{y[2]}'\n" + | |
"add_foreign_key '#{y[0]}', ['#{y[1]}'], '#{y[3]}', ['#{y[4]}'], on_update: :no_action, on_delete: :no_action, name: '#{y[2]}'" | |
};nil | |
puts z.join("\n\n");nil | |
# reverse to default :restrict | |
z = x.map {|y| | |
"remove_foreign_key :#{y[0]}, column: '#{y[1]}', name: '#{y[2]}'\n" + | |
"add_foreign_key '#{y[0]}', ['#{y[1]}'], '#{y[3]}', ['#{y[4]}'], on_update: :restrict, on_delete: :restrict, name: '#{y[2]}'" | |
};nil | |
puts z.join("\n\n");nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment