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

Configurable generation of add_index for references columns

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
This commit is contained in:
Michał Łomnicki 2011-02-01 23:27:26 +01:00 committed by Santiago Pastorino
parent 5b42e96602
commit 4e39072017
3 changed files with 44 additions and 0 deletions

View file

@ -10,6 +10,7 @@ module ActiveRecord
class_option :migration, :type => :boolean class_option :migration, :type => :boolean
class_option :timestamps, :type => :boolean class_option :timestamps, :type => :boolean
class_option :parent, :type => :string, :desc => "The parent class for the generated model" 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 def create_migration_file
return unless options[:migration] && options[:parent].nil? return unless options[:migration] && options[:parent].nil?

View file

@ -9,8 +9,10 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<% end -%> <% end -%>
end end
<% if options[:indexes] %>
<% attributes.select {|attr| attr.reference? }.each do |attribute| -%> <% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
add_index :<%= table_name %>, :<%= attribute.name %>_id add_index :<%= table_name %>, :<%= attribute.name %>_id
<% end -%> <% end -%>
<% end %>
end end
end end

View file

@ -203,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase
content = capture(:stderr){ run_generator ["object"] } content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content assert_match /The name 'Object' is either already used in your application or reserved/, content
end 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 end