diff options
Diffstat (limited to 'railties')
-rw-r--r-- | railties/lib/rails/generators/generated_attribute.rb | 4 | ||||
-rw-r--r-- | railties/test/generators/migration_generator_test.rb | 5 | ||||
-rw-r--r-- | railties/test/generators/model_generator_test.rb | 16 |
3 files changed, 20 insertions, 5 deletions
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index f16bd8e082..77a3dbf9a2 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -159,6 +159,10 @@ module Rails options.delete(:required) options[:null] = false end + + if reference? && !polymorphic? + options[:foreign_key] = true + end end end end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index c2c8e2abad..0803699968 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -189,8 +189,9 @@ class MigrationGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/#{migration}.rb" do |content| assert_method :change, content do |change| - assert_match(/add_foreign_key :books, :authors/, change) - assert_no_match(/add_foreign_key :books, :distributors/, change) + assert_match(/add_reference :books, :author,.*\sforeign_key: true/, change) + assert_match(/add_reference :books, :distributor/, change) # sanity check + assert_no_match(/add_reference :books, :distributor,.*\sforeign_key: true/, change) end end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index ac7a0acf6b..9dc438fe3c 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -407,13 +407,23 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end + def test_foreign_key_is_not_added_for_non_references + run_generator ["account", "supplier:string"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match(/foreign_key/, up) + end + end + end + def test_foreign_key_is_added_for_references run_generator ["account", "supplier:belongs_to", "user:references"] assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_match(/add_foreign_key :accounts, :suppliers/, up) - assert_match(/add_foreign_key :accounts, :users/, up) + assert_match(/t\.belongs_to :supplier,.*\sforeign_key: true/, up) + assert_match(/t\.references :user,.*\sforeign_key: true/, up) end end end @@ -423,7 +433,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_no_match(/add_foreign_key :accounts, :suppliers/, up) + assert_no_match(/foreign_key/, up) end end end |