Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

rails 3.2 migration cannot add index to create_table in change method

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?

question from:https://stackoverflow.com/questions/9713015/rails-3-2-migration-cannot-add-index-to-create-table-in-change-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can still add an index as a part of a "change" migration. You just have to do it outside of the call to create_table:

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
    end

    add_index :statistics, [:name, :item_id]
  end
end

This correctly creates the table and then the index on an "up" migration and drops the index and then the table on a "down" migration.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...