Emre Emre - 7 months ago 18
SQL Question

Rails rollback, change type and migrate again

I have a requests table;

class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.string :from
t.string :to

t.timestamps null: false
end
end
end


I would like to rollback the database with
rake db:rollback STEP = 5

destroy the Request model and create request table with;

t.datetime :from
t.datetime :to


However, I have a migration table to Request model on STEP = 2,

class AddStatusToRequest < ActiveRecord::Migration
def change
add_column :requests, :status, :string, :default => "Pending"
end
end


The problem is, if I destroy Request table and create new Request table with datetime types it creates after STEP = 2 and when I
rake db:migrate
rails does not add Status column to Request table. How can I overcome this?

Answer

You can create a new migration to change the column type using change_column:

command line: rails g migration change_request_to_from_column_types'

new migration:

class ChangeRequestToFromColumnTypes < ActiveRecord::Migration
  def change
    change_column :requests, :from, :datetime
    change_column :requests, :to, :datetime
  end
end
Comments