你如何在Rails中更改列数据类型?

29 浏览
0 Comments

你如何在Rails中更改列数据类型?

我想使用 Rails 修改数据库中几列的数据类型。我尝试了以下代码,但是出现了错误,错误消息为“G::DuplicateColumn: ERROR: column \'geography\' of Relation \'town_health_records\' already exists”。

我尝试创建一个新的迁移文件,并运行rake db:migrate,如下所示:

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

admin 更改状态以发布 2023年5月21日
0
0 Comments

添加一个迁移:

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
0 Comments

建议使用t.change而非t.string。你现在做的是尝试声明一个名为geography的另一列,因此你看到了那个错误。

查看change_table方法的API文档

因此,你的迁移文件应该如下:

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

0