2013-12-11 17 views
3

我想使用Rails更改數據庫中幾個列的數據類型。我已經嘗試了下面的代碼,但是我得到一個錯誤「G :: DuplicateColumn:ERROR:關係」town_health_records「的列」地理位置「已經存在」你如何在rails中更改列數據類型?

我試着創建一個新的遷移文件並運行rake db:migrate as如下圖所示:

class UpdateColumns < ActiveRecord::Migration 
    def change 
    change_table :town_health_records do |t| 
    t.string :geography 
    t.string :total_pop_year_2005 
    t.string :age_0_19_year_2005 
    t.string :age_65_up_year_2005 
    t.string :per_capita_income_year_2000 
    t.string :persons_below_200pct_poverty_yr_2000 
    t.float :pct_all_persons_below_200pct_poverty_year_2000 
    t.float :pct_adequacy_prenatal_care_kotelchuck 
    t.float :pct_c_sections_2005_2008 
    t.integer :num_infant_deaths_2005_2008 
    t.float :infant_mortality_rate_2005_2008 
    t.float :pct_low_birthweight_2005_2008 
    t.float :pct_multiple_births_2005_2008 
    t.float :pct_publicly_financed_prenatal_care_2005_2008 
    t.float :pct_teen_births_2005_2008 


     t.timestamps 
    end 
    end 
end 

我只需要將數據類型更改爲字符串以下列:

:total_pop_year_2005 
:age_0_19_year_2005 
:age_65_up_year_2005 
:per_capita_income_year_2000 
:persons_below_200pct_poverty_yr_2000 
+0

http://stackoverflow.com創建表/ questions/2799774/rails-migration-for-change-column這個給你你需要的信息 – RustyToms

+0

另外,你應該在使用PostgreSQL的時候忘記':string'並且使用':text'(除非你有一個限制數據庫中字段大小的好理由)。 'varchar(n)'幾乎是稍微昂貴的'text'版本,它有一個大小限制,你顯然不關心,因爲你沒有任何':limit's。 –

回答

2

嘗試t.change而不是t.string。你現在正在做的是試圖聲明另一個名爲geography的列,這就是你看到這個錯誤的原因。

查看API Documentationchange_table方法。

所以,你的遷移文件應該是這樣:

class UpdateColumns < ActiveRecord::Migration 
    def change 
    change_table :town_health_records do |t| 
     t.change :total_pop_year_2005, :string 
     t.change :age_0_19_year_2005, :string 
     ... 
    end 
    end 
end 
2

添加遷移:

def change 
    change_column :town_health_records, :total_pop_year_2005, :string 
    change_column :town_health_records, :age_0_19_year_2005, :string 
    change_column :town_health_records, :age_65_up_year_2005, :string 
    change_column :town_health_records, :per_capita_income_year_2000, :string 
    change_column :town_health_records, :persons_below_200pct_poverty_yr_2000, :string 
end 

或回滾,然後再

+0

rails方式是添加一個新的遷移來實現更改,而不是回滾。 – Red