Difender
Difender

Reputation: 525

Changing a field type with a migration

I have an Info table with a age field which is an int

But I want to change the type to a date so that I can calculate the age dynamically.

So I did this migration :

class ChangeDateFormatInInfo < ActiveRecord::Migration[5.0]
  def change
    change_column :infos, :age, :date
  end
end

But there was a DatatypeMismatch

column "age" cannot be cast automatically to type date

So I changed it to :

change_column :infos, :age, :date, 'USING age::date'

But it still gives me

migrateTypeError: no implicit conversion of Symbol into Integer

I don't really get it, I'm telling it to convert it, so what am I doing wrong ?

Upvotes: 0

Views: 243

Answers (2)

puneet18
puneet18

Reputation: 4427

You have to first remove the column and then add it again with new datatype.

So try below code:

rails g migration ChangeDateFormatInInfo

then goto db/migrate/change_date_format_in_info_xxxx.rb file and open it.

Add below code in migration file:

class ChangeDateFormatInInfo < ActiveRecord::Migration[5.0]
  def change
    remove_column :infos, :age
    add_column :infos, :age, :date
  end
end

then run command:

rake db:migrate

Upvotes: 1

Difender
Difender

Reputation: 525

Didn't thought about it, I just did a migration to drop the field, and another one to add a field. Done now :)

rails g migration remove_age_from_info age:integer

rails g migration add_age_to_info age:date

Upvotes: 0

Related Questions