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

5
我想使用Rails更改数据库中几个列的数据类型。 我尝试了以下代码,但出现错误“G :: DuplicateColumn:ERROR:关系“ town_health_records”的列“地理”已经存在”
我尝试创建一个新的迁移文件并运行以下 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

这个链接提供了你需要的信息。它是关于Rails迁移更改列的问题。 - RustyToms
顺便提一下,当使用PostgreSQL时,您应该忘记:string,并只使用:text(除非您有一个在数据库中限制字段大小的好理由)。 varchar(n)基本上是text的略微更昂贵的版本,它具有大小限制,而您显然不关心,因为您没有任何:limit - mu is too short
3个回答

5
尝试使用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

4

添加迁移:

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

或者回滚,然后再创建表


Rails 的方式是添加一个新的迁移来实现更改,而不是执行回滚。 - pyfork

0
如果你需要更改多列,使用change_table。此外,请确保将类名更改为更易于维护的名称,例如ChangeTownHealthRecordsColumns:
class ChangeTownHealthRecordsColumns < ActiveRecord::Migration
  def change
    change_table :town_health_records do |t|
      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
  end
end

如果您对这个主题感兴趣,可以阅读这篇文章了解更多信息:https://kolosek.com/rails-change-database-column


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接