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
You can use the change method with the rename_column definition in your migrations files to update a single column name in your database.
First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.
Try t.change
instead of t.string
. What you're doing right now is trying to declare another column named geography, which is why you're seeing that error.
Take a look at the API Documentation for the change_table
method.
So, your migration file should look like:
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
add a migration:
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
or roll back and then create the table again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With