Permalink
Browse files

Make `:index` in migrations work with all column types

  • Loading branch information...
1 parent dbbcc83 commit 9a0d35e820464f872b0340366dded639f00e19b9 @schuetzm schuetzm committed Feb 20, 2014
View
5 activerecord/CHANGELOG.md
@@ -1,3 +1,8 @@
+* The `:index` option in migrations, which previously was only available for
+ `references`, now works with any column types.
+
+ *Marc Schütz*
+
* Add support for counter name to be passed as parameter on `CounterCache::ClassMethods#reset_counters`.
*jnormore*
View
19 activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -99,6 +99,8 @@ def [](name)
# Specifies the precision for a <tt>:decimal</tt> column.
# * <tt>:scale</tt> -
# Specifies the scale for a <tt>:decimal</tt> column.
+ # * <tt>:index</tt> -
+ # Create an index for the column. Can be either <tt>true</tt> or an options hash.
#
# For clarity's sake: the precision is the number of significant digits,
# while the scale is the number of digits that can be stored following
@@ -163,18 +165,21 @@ def [](name)
# What can be written like this with the regular calls to column:
#
# create_table :products do |t|
- # t.column :shop_id, :integer
- # t.column :creator_id, :integer
- # t.column :name, :string, default: "Untitled"
- # t.column :value, :string, default: "Untitled"
- # t.column :created_at, :datetime
- # t.column :updated_at, :datetime
+ # t.column :shop_id, :integer
+ # t.column :creator_id, :integer
+ # t.column :item_number, :string
+ # t.column :name, :string, default: "Untitled"
+ # t.column :value, :string, default: "Untitled"
+ # t.column :created_at, :datetime
+ # t.column :updated_at, :datetime
# end
+ # add_index :products, :item_number
#
# can also be written as follows using the short-hand:
#
# create_table :products do |t|
# t.integer :shop_id, :creator_id
+ # t.string :item_number, index: true
# t.string :name, :value, default: "Untitled"
# t.timestamps
# end
@@ -210,6 +215,8 @@ def column(name, type, options = {})
raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
end
+ index_options = options.delete(:index)
+ index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
@columns_hash[name] = new_column_definition(name, type, options)
self
end
View
10 activerecord/test/cases/migration/columns_test.rb
@@ -274,6 +274,16 @@ def test_removing_and_renaming_column_preserves_custom_primary_key
ensure
connection.drop_table(:my_table) rescue nil
end
+
+ def test_column_with_index
+ connection.create_table "my_table", force: true do |t|
+ t.string :item_number, index: true
+ end
+
+ assert connection.index_exists?("my_table", :item_number, name: :index_my_table_on_item_number)
+ ensure
+ connection.drop_table(:my_table) rescue nil
+ end
end
end
end

0 comments on commit 9a0d35e

Please sign in to comment.