Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
linjunhalida Avatar asked Mar 15 '12 02:03

linjunhalida


2 Answers

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.

like image 149
Brandan Avatar answered Sep 29 '22 05:09

Brandan


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 
like image 30
linjunhalida Avatar answered Sep 29 '22 05:09

linjunhalida