aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb6
-rw-r--r--activerecord/test/cases/migration/foreign_key_test.rb9
2 files changed, 14 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index 18e73b0200..5a863717e5 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -682,7 +682,11 @@ module ActiveRecord
def foreign_key_name(table_name, options) # :nodoc:
options.fetch(:name) do
- "#{table_name}_#{options.fetch(:column)}_fk"
+ identifier = "#{table_name}_#{options.fetch(:column)}_fk"
+ if identifier.length > allowed_index_name_length
+ raise ArgumentError, "Foreign key name '#{identifier}' is too long; the limit is #{allowed_index_name_length} characters"
+ end
+ identifier
end
end
diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb
index c69fc18d82..815c6b2955 100644
--- a/activerecord/test/cases/migration/foreign_key_test.rb
+++ b/activerecord/test/cases/migration/foreign_key_test.rb
@@ -136,6 +136,15 @@ module ActiveRecord
assert_equal :nullify, fk.on_update
end
+ def test_add_foreign_key_with_too_long_identifier
+ with_example_table @connection, "long_table_name_will_result_in_a_long_foreign_key_name", "rocket_id integer" do
+ e = assert_raises(ArgumentError) do
+ @connection.add_foreign_key "long_table_name_will_result_in_a_long_foreign_key_name", "rockets"
+ end
+ assert_match(/^Foreign key name 'long_table_name_will_result_in_a_long_foreign_key_name_rocket_id_fk' is too long;/, e.message)
+ end
+ end
+
def test_remove_foreign_key_inferes_column
@connection.add_foreign_key :astronauts, :rockets