12

我試圖在表中的特定列之後向表中添加一列。 這裏是我做過什麼:ruby​​ on rails在特定列名之後添加一列

rails generate migration add_reaction_id_to_patient_allergies reaction_id: integer :after => 'patient_id' 

這裏是我的移民文件看起來像:

class AddReactionIdToPatientAllergies < ActiveRecord::Migration 
    def change 
    add_column :patient_allergies, :reaction_id, :string 
    add_column :patient_allergies, :integer, :string 
    add_column :patient_allergies, :, :after 
    add_column :patient_allergies, :=, :string 
    end 
end 

我不認爲命令進行得很順利。我在上面的文件中看到一個'='。我不認爲它應該在那裏。有人能告訴我我是否錯過了任何東西嗎?

如果是這樣,我該如何解決上述問題?

回答

38

我懷疑它允許你實際上rake db:migrate這個遷移,所以你不應該回滾。只需卸下底部的三個add_column S和重新裝上一個與

add_column :patient_allergies, :reaction_id, :integer, after: :patient_id 

,它應該是罰款遷移。對於未來的參考,這就是你輸入的命令應該是什麼樣子:

rails generate migration add_reaction_id_to_patient_allergies reaction_id:integer 

的空間之前integer作出發電機認爲這是一個新的列。可悲的是,你不能在命令行上使用Ruby語法(a => b)。

+1

@michael只需在這個好的答案中再添加一件事,就可以撤消一次成功但不需要的遷移,您可以執行rake db:rollback - 這將反轉最近的遷移。您可以通過重複進一步。我經常發現自己正在進行一些小的調整,例如設置默認值或列順序 – Polsonby 2014-01-07 11:28:49

+3

':after'選項看起來不包含在[API文檔]中(http://api.rubyonrails.org/classes /ActiveRecord/Migration.html),至少在Rails 4.2.3中。嘗試後發現:遷移正常但未應用排序。 – nandinga 2015-08-18 17:26:29

+0

@nandinga它看起來像最新的Rails中的[ColumnDefinition]類(https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L13)仍然支持''後''選項,雖然我還沒有在最後幾個版本的Rails上測試過。 – piersadrian 2015-08-25 22:36:21