2010-09-07 76 views
1

在Rails 3,Rails 3中,我添加了一個表,然後加入柱中,現在我要添加一個索引

我創建的表有遷移,然後加入遷移列這產生的has_many ,belongs_to的關係....

我然後跑耙分貝:遷移

我想現在添加一個索引,因爲我忘了補充它之前,我可以遷移。我可以將其添加到其中一個現有遷移文件(創建表中的一個)還是需要創建一個新遷移以將索引添加到現有表中?

感謝

回答

4

我通常會創建一個新的遷移,如果我忘記了類似的東西(尤其是如果我已經在生產中已遷移)。但是,如果你仍然在發展,那麼你就可以改變你的最後一個遷移文件,並使用重做rake命令:

rake db:migrate:redo 

還有:

rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n). 

運行這個命令來查看所有不同的耙任務:

rake -T db 

這裏是Rails指南在談論它的部分: http://guides.rubyonrails.org/migrations.html#rolling-back

3

如果您想在不丟失數據的情況下添加索引,則必須創建一個新遷移來添加索引。假設你的模型被稱爲Widget和外國模型被稱爲Zidget;

rails generate migration AddIndexToWidgets 

和你的新的遷移文件中的db/migrate/xxxxxxxxxx_add_index_to_widgets

class AddIndexToWidgets < ActiveRecord::Migration 
    def self.up 
    change_table :widgets do |t| 
     t.index :zidget_id # add ':unique => true' option if necessary 
    end 
    end 

    def self.down 
    change_table :widgets do |t| 
     t.remove_index :zidget_id 
    end 
    end 
end 

然後rake db:migrate像往常一樣就萬事大吉了,你有你的索引列。


更新:如果要添加一個指標是你正在做的,有寫同樣的事情,更簡潔的方式。結果沒有區別。只是如果你的表有多個變更,前面的語法就是爲了幹你的代碼。

class AddIndexToWidgets < ActiveRecord::Migration 
    def self.up 
    add_index :widgets, :zidget_id # add ':unique => true' option if necessary 
    end 

    def self.down 
    remove_index :widgets, :column => :zidget_id 
    end 
end 
+0

很酷。你需要Rails 3中的change_table部分嗎?我沒有這個工作呢? – AnApprentice 2010-09-08 00:45:02

+0

這只是其中一種可能的方式。我編輯了一個更簡潔的答案。它們都對2.x和3都有好處 – edgerunner 2010-09-09 09:47:47

相關問題