How do you change column data type in rails?

Viewed 7709

I'd like to change the data type for several columns in a database using Rails. I have tried the following code but I get an error "G::DuplicateColumn: ERROR: column "geography" of relation "town_health_records" already exists"

I have tried creating a new migration file and running rake db:migrate as shown below:

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

I only need to change the data type to string for the following columns :

: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
3 Answers

If you are changing several columns use change_table. Plus, be sure to change your class name to something more maintainable like 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

If you are interested in this topic you can read more in this article: https://kolosek.com/rails-change-database-column.

Related