Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I drop a column in Rails?

The change method can be used to drop a column in Rails 4 applications, but should not be used in Rails 3. I updated my answer accordingly. You can also use remove_column :table_name, :column_name, :type, :options within the change method, since if you specify the type reverting the migration is possible.

How do you take out a column?

To remove a single column, select the column you want to remove, and then select Home > Remove Columns > Remove Columns. To remove several columns, select the columns by using Ctrl + Click or Shift + Click.


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

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(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


If want to remove the index too, you do with migration too:

rails g migration remove_post_id_from_comments post_id:integer:index

migration file:

class RemovePostIdFromComments < ActiveRecord::Migration
  def change
    remove_index :comments, :post_id
    remove_column :comments, :post_id, :integer
  end
end

then run: rake db:migrate


Do you need to specify the type?

Why not just remove_column :sample_apps, :country or remove_column :comments, :post_id for the samples here? Seems to work and removes a chance for error (text or string).