2014-11-23 130 views
0

我在調查模型建立的社團如下Ruby on Rails的 - 反向add_column,add_index遷移

attr_accessible :name, :questions_attributes 
has_many :questions 

和有關模型

attr_accessible :content, :survey_id, :answers_attributes 
belongs_to :survey 

我有增加了question_id調查表遷移 但我意識到這種遷移並不是必需的,因爲我已經在模型中定義了它們的關聯。 我的理解是否正確?

如果我的理解是正確的,我想反轉該遷移。

我已經添加了最後兩行,從remove開始,然後跑rake db:migrate 但它什麼也沒做。

def change 
    add_column :surveys, :question_id, :integer 
    add_index :surveys, :question_id 
    remove_column :surveys, :question_id, :integer 
    remove_index :surveys, :question_id 
end 

回答

2

根據我的理解,您要回滾遷移。如果是這樣,那麼你可以使用下面的語法爲

rake db:rollback STEP=n 

     or 


rake db:migrate:down VERSION=<version_number_of_migration> 

這rollsback

+0

您好,感謝您的輸入「遷移文件的時間戳」。那麼是不是有必要首先將這個索引添加到關聯表中,因爲它們已經在模型中定義了? – 2014-11-23 11:15:20

+0

您的意思是調查表中的question_id? – 2014-11-23 11:20:02

+0

是的,我想知道在模型中定義關聯時是否需要添加此列 – 2014-11-23 11:23:16

2
def up 
    add_column :surveys, :question_id, :integer 
    add_index :surveys, :question_id 
end 

def down 
    remove_index :surveys, :question_id 
    remove_column :surveys, :question_id 
end 

up方法是在rake db:migrate執行特定遷移,向下方法上rake db:rollback 執行你不能僅僅依賴在change方法中,由於需要進行回滾的順序(首先刪除索引,然後刪除列)

編輯: Act ually,你可以在Rails的只有change做3.2+

def change 
    add_column :surveys, :question_id, :integer 
    add_index :surveys, :question_id 
end 
0

是其始終neccessary寫遷移到在調查表中添加question_id

只有聲明協會是不夠的

你migrtaion應該喜歡這個

DEF改變 add_reference:調查:問題,指數:真正 結束

如果您僅在系統中進行更改,則可以在任何時候回滾遷移。不要試圖回滾一旦這些移民在不同的環境

跑到回滾耙分貝:遷移:回滾VERSION =