Rails 5: How to remove a column from a database?

To remove a column(country here) from table(sample_case)

rails generate migration RemoveCountryfromSampleCase country:string

Above command should generate a file YYYYMMDDHHMMSS_remove_countryfrom_sample_case.rb. under db/migrate folder

class RemoveCountryFromSampleCase < ActiveRecord::Migration[5.0]
  def change
    remove_column :sample_case, :country, :string
  end
end

In my case (I was doing it for more than two columns) only this appears

 class RemoveCountryFromSampleCase < ActiveRecord::Migration[5.0]
  def change
  end
 end

remove_column line was not there so I added it manually and then fired the command

rails db:migrate

and it worked for me.

References https://stackoverflow.com/a/2963582 & Ruby guide on Active Record migration https://edgeguides.rubyonrails.org/active_record_migrations.html


Create migration file:

$ rails generate migration RemoveCountryFromSampleApps country:string

In generated migration file:

class RemoveCountryFromSampleApps < ActiveRecord::Migration
 def change
   remove_column :sample_apps, :country, :string
 end
end

Then run:

 rake db:migrate

To remove a column with migration:

rails g migration Remove..From.. col1:type col2:type col3:type

In your case:

rails g migration RemoveCountryFromSampleApps country:string

This will generate the following migration in Rails 5.0:

class RemoveCountryFromSampleApps < ActiveRecord::Migration[5.0]
  def change
    remove_column :sample_apps, :country, :string
  end
end