diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index c75abd043c..f7caa43ac8 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -10,6 +10,7 @@ module ActiveRecord class_option :migration, :type => :boolean class_option :timestamps, :type => :boolean class_option :parent, :type => :string, :desc => "The parent class for the generated model" + class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns" def create_migration_file return unless options[:migration] && options[:parent].nil? diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb index cd2552d9b8..e573e908a7 100644 --- a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb @@ -9,8 +9,10 @@ class <%= migration_class_name %> < ActiveRecord::Migration <% end -%> end +<% if options[:indexes] %> <% attributes.select {|attr| attr.reference? }.each do |attribute| -%> add_index :<%= table_name %>, :<%= attribute.name %>_id <% end -%> +<% end %> end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index b86859666e..6b2fd8b9ee 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -203,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase content = capture(:stderr){ run_generator ["object"] } assert_match /The name 'Object' is either already used in your application or reserved/, content end + + def test_index_is_added_for_belongs_to_association + run_generator ["account", "supplier:belongs_to"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match /add_index/, up + end + end + end + + def test_index_is_added_for_references_association + run_generator ["account", "supplier:references"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match /add_index/, up + end + end + end + + def test_index_is_skipped_for_belongs_to_association + run_generator ["account", "supplier:belongs_to", "--no-indexes"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match /add_index/, up + end + end + end + + def test_index_is_skipped_for_references_association + run_generator ["account", "supplier:references", "--no-indexes"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match /add_index/, up + end + end + end + end