Alex Rivera | Logout

rails 3.2 migration cannot add index to create_table in change method

Asked 2012-03-15T02:02:30.917
37

here is my migration in rails 3.2.2:

class CreateStatistics < ActiveRecord::Migration
  def change
    create_table :statistics do |t|
      t.string :name
      t.integer :item_id
      t.integer :value
      t.text :desc

      t.timestamps
      t.index [:name, :item_id]
    end

  end
end

and here is the migrate error:

==  CreateStatistics: migrating ===============================================
-- create_table(:statistics)
ActiveRecord::ConnectionAdapters::TableDefinition
rake aborted!
An error has occurred, all later migrations canceled:

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

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

what is the right way to create a index?

Edit
Report

3 Answers

4

so I change it to the old way, and it works. and I think there is a new way doing this by using change method.

class CreateStatistics < ActiveRecord::Migration
  def up
    create_table :statistics do |t|
      t.string :name
      t.integer :item_id
      t.integer :value
      t.text :desc

      t.timestamps
    end
    add_index :statistics, [:name, :item_id]
  end

  def down
    drop_table :statistics
  end
end
answered 2012-03-15T02:18:09.467
3

If you have more than one index and don't want to repeat the table name several times in individual add_index calls, you can use a change_table block that follows the create_table.

create_table :user_states do |t|
  t.references :user, :null => false
  t.integer :rank
  t.integer :status_code
end

change_table :user_states do |t|
  t.index [:rank, :status_code]
end
answered 2012-11-01T17:03:02.333
1

It looks like create_table yields an ActiveRecord::ConnectionAdapters::TableDefinition class. This class does not contain the method index. Instead, change_table appears to yield an ActiveRecord::ConnectionAdapters::Table class which includes this index method.

If you want to add an index during a create_table migration, try this:

class CreateStatistics < ActiveRecord::Migration
  def self.up
    create_table :statistics do |t|
      t.string :name
      t.integer :item_id
      t.integer :value
      t.text :desc

      t.timestamps
    end

    add_index :statistics, :name
    add_index :statistics, :item_id
  end

  def self.down
    drop_table :statistics
  end
end
answered 2012-03-15T02:09:33.093

Your Answer