1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

SQLite3 adapter alter_table method restores foreign keys

Related to #33520
This commit is contained in:
Yasuo Honda 2018-08-06 11:38:44 +00:00
parent 924f443716
commit 33ce73edf1
3 changed files with 26 additions and 1 deletions

View file

@ -1,3 +1,7 @@
* SQLite3 adapter `alter_table` method restores foreign keys.
*Yasuo Honda*
* Add environment & load_config dependency to `bin/rake db:seed` to enable
seed load in environments without Rails and custom DB configuration

View file

@ -409,13 +409,14 @@ module ActiveRecord
def alter_table(table_name, options = {})
altered_table_name = "a#{table_name}"
options_to_restore = { foreign_keys: foreign_keys(table_name) }
caller = lambda { |definition| yield definition if block_given? }
transaction do
disable_referential_integrity do
move_table(table_name, altered_table_name,
options.merge(temporary: true))
move_table(altered_table_name, table_name, &caller)
move_table(altered_table_name, table_name, options_to_restore, &caller)
end
end
end
@ -446,6 +447,13 @@ module ActiveRecord
primary_key: column_name == from_primary_key
)
end
if options[:foreign_keys]
options[:foreign_keys].each do |fk|
@definition.foreign_key(fk.to_table, fk.options)
end
end
yield @definition if block_given?
end
copy_table_indexes(from, to, options[:rename] || {})

View file

@ -64,6 +64,19 @@ if ActiveRecord::Base.connection.supports_foreign_keys_in_create?
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
end
def test_rename_column_of_child_table
rocket = Rocket.create!(name: "myrocket")
rocket.astronauts << Astronaut.create!
@connection.rename_column :astronauts, :name, :astronaut_name
foreign_keys = ActiveRecord::Base.connection.foreign_keys("astronauts")
fk = foreign_keys.first
assert_equal "myrocket", Rocket.first.name
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
end
end
end
end