From b8e1f202676b4788c56241b124c401beff9f4014 Mon Sep 17 00:00:00 2001 From: Chris Sinjakli Date: Mon, 2 Feb 2015 23:41:12 +0000 Subject: Generate consistent names for foreign keys --- activerecord/CHANGELOG.md | 9 +++++++++ .../connection_adapters/abstract/schema_statements.rb | 6 +++++- activerecord/test/cases/migration/foreign_key_test.rb | 4 ++-- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 3a0c32e66d..af692adad6 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,12 @@ +* Foreign keys added by migrations were given random, generated names. This + meant a different `structure.sql` would be generated every time a developer + ran migrations on their machine. + + The generated part of foreign key names is now a hash of the table name and + column name, which is consistent every time you run the migration. + + *Chris Sinjakli* + * Validation errors would be raised for parent records when an association was saved when the parent had `validate: false`. It should not be the responsibility of the model to validate an associated object unless the 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 f905669a24..ed32997d25 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1,4 +1,6 @@ require 'active_record/migration/join_table' +require 'active_support/core_ext/string/access' +require 'digest' module ActiveRecord module ConnectionAdapters # :nodoc: @@ -990,8 +992,10 @@ module ActiveRecord end def foreign_key_name(table_name, options) # :nodoc: + identifier = "#{table_name}_#{options.fetch(:column)}_fk" + hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) options.fetch(:name) do - "fk_rails_#{SecureRandom.hex(5)}" + "fk_rails_#{hashed_identifier}" end end diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index 78d9dd90a3..333fb7d4c6 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -57,7 +57,7 @@ module ActiveRecord assert_equal "rockets", fk.to_table assert_equal "rocket_id", fk.column assert_equal "id", fk.primary_key - assert_match(/^fk_rails_.{10}$/, fk.name) + assert_equal("fk_rails_78146ddd2e", fk.name) end def test_add_foreign_key_with_column @@ -71,7 +71,7 @@ module ActiveRecord assert_equal "rockets", fk.to_table assert_equal "rocket_id", fk.column assert_equal "id", fk.primary_key - assert_match(/^fk_rails_.{10}$/, fk.name) + assert_equal("fk_rails_78146ddd2e", fk.name) end def test_add_foreign_key_with_non_standard_primary_key -- cgit v1.2.3