2016-01-14 70 views
15

我有這個表:更改列名的Rails

class CreateShoes < ActiveRecord::Migration 
    def change 
    create_table :shoes do |t| 
     t.string :name 
     t.boolean :leather 
     t.integer :season 

     t.timestamps null: false 
    end 
    end 
end 

的 '季節' 一欄被稱爲 'season_id'。我知道我必須編寫't.rename:season,:season_id',如http://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers中所解釋的,但我無法找到正確的語法。它應該是?

class CreateShoes < ActiveRecord::Migration 
    def change 
    create_table :shoes do |t| 
     t.string :name 
     t.boolean :leather 
     t.integer :season 

     t.timestamps null: false 
    end 

    change_table :products do |t| 
     t.rename :season, :season_id 
    end 

    end 
end 

不起作用。我需要在Mac控制檯中做什麼?謝謝!

+4

你爲什麼要在同一遷移中重命名它?回滾並將其修復到'create_table'中,或者創建一個新的遷移。你也可以直接寫'rename_column:shoes,season,season_id',而不是把它放在一個塊中。 –

+0

我不知道我在做什麼。學習:)忘了補充表中有數據。創造新的遷移意味着新的「變化」? thx – Pere

+1

這意味着有一個新的遷移,它有自己的'change'方法。 –

回答

47

運行在控制檯:

$ rails g migration rename_season_to_season_id 

現在文件db/migrate/TIMESTAMP_rename_season_to_season_id.rb包含以下內容:

class RenameSeasonToSeasonId < ActiveRecord::Migration 
    def change 
    end 
end 

將其修改爲:

class RenameSeasonToSeasonId < ActiveRecord::Migration 
    def change 
    rename_column :shoes, :season, :season_id 
    end 
end 

然後在控制檯中運行$ rake db:migrate

2

無論哪種解決您的遷移做

rake db:rollback db:migrate 

,或進行另一個遷移,像這樣:

rename_column :shoes, :season, :season_id if column_exists?(:shoes, :season) && !column_exists?(:shoes, :season_id) 

,然後做

rake db:migrate 
0

如果你的意圖是比你例子遷移不決策意識重命名錶列:)......取而代之的是

class CreateShoes < ActiveRecord::Migration 
    def change 
    create_table :shoes do |t| 
     t.string :name 
     t.boolean :leather 
     t.integer :season 

     t.timestamps null: false 
    end 

    change_table :products do |t| 
     t.rename :season, :season_id 
    end 

    end 
end 

你只需要表變更遷移,像這樣(Rails會照顧回滾您):

class RenameSessionColumnInsideShoes < ActiveRecord::Migration 
    def change 
    change_table :products do |t| 
     t.rename :season, :season_id 
    end 
    end 
end 

rename表對象的方法在Rails是有效的方法,你可以在Rails的源代碼中看到

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L582