index(column_name, options = {})
public

Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols. See SchemaStatements#add_index

Examples
Creating a simple index
 t.index(:name)
Creating a unique index
 t.index([:branch_id, :party_id], :unique => true)
Creating a named index
 t.index([:branch_id, :party_id], :unique => true, :name => 'by_branch_party')

8Notes

Re: Doesn't work? Don't think it ever has.

bradwerth · Sep 16, 20101 thank

Instead of

create_table :user_follows, :force => true do |t|
  t.references :user
  t.references :followed_user
  t.timestamps
  t.index :user
  t.index :followed_user
end

Try

create_table :user_follows, :force => true do |t|
  t.references :user
  t.references :followed_user
  t.timestamps
end

index :user_follows , :user
index :user_follows , :followed_user

It looks like the provided examples are incorrect...

still broken

ssoroka · Oct 22, 20101 thank

add_index is a different method. I think this is just a bug and it's broken.

Doesn't work? Don't think it ever has.

ssoroka · Sep 9, 2010

This doesn't work for me. I do something like:

create_table :user_follows, :force => true do |t|
  t.references :user
  t.references :followed_user
  t.timestamps
  t.index :user
  t.index :followed_user
end

and I get:

rake aborted!
An error has occurred, all later migrations canceled:

undefined method `index' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x106c02220>

add_index has the same effect.

Or maybe...

bradwerth · Sep 22, 2010

or maybe

add_index :user_follows , :user
add_index :user_follows , :followed_user

index doesn't work

druva · Nov 29, 2011

@ssoroka even I'm having same issue. how did you resolve it?

Not working in create_table

schmidt · Feb 15, 2012

When using the index method within a +create_table+ statement, it does not have any side effect - at least not in MySQL.

create_table :comment do |t|
t.belongs_to :post

t.timestamps

# not working inside create_table !
t.index :post_id
end

It is working properly in +change_table+ though

change_table :comment do |t|
t.belongs_to :user

# this works inside change_table
t.index :user_id
end

Unfortunately this flaw is not reported in any way. The index is just not created.

I have only tested this with the mysql2 driver in Rails 2.3.x. I'm not sure, if this happens in other versions/adapters as well.

@ssoroka and @drova and future readers

schmidt · Feb 15, 2012

I guess these two have already found a solution, but future readers might have not. index and references do not map perfectly

change_table :foo do |t|
t.references :bar
t.index      :bar_id
end

references gets the model name while index gets the column name.

This method does not work.

jarl-dk · Jun 4, 2012

It's an old problem, reported back in 2010, just reopened issue:

http://github.com/rails/rails/issues/6620