How to drop columns using Rails migration
remove_column :table_name, :column_name
For instance:
remove_column :users, :hobby
would remove the hobby Column from the users table.
For older versions of Rails
ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype
For Rails 3 and up
rails generate migration RemoveFieldNameFromTableName field_name:datatype
Rails 4 has been updated, so the change method can be used in the migration to drop a column and the migration will successfully rollback. Please read the following warning for Rails 3 applications:
Rails 3 Warning
Please note that when you use this command:
rails generate migration RemoveFieldNameFromTableName field_name:datatype
The generated migration will look something like this:
def up
remove_column :table_name, :field_name
end
def down
add_column :table_name, :field_name, :datatype
end
Make sure to not use the change method when removing columns from a database table (example of what you don't want in the migration file in Rails 3 apps):
def change
remove_column :table_name, :field_name
end
The change method in Rails 3 is not smart when it comes to remove_column, so you will not be able to rollback this migration.
In a rails4 app it is possible to use the change method also for removing columns. The third param is the data_type and in the optional forth you can give options. It is a bit hidden in the section 'Available transformations' on the documentation .
class RemoveFieldFromTableName < ActiveRecord::Migration
def change
remove_column :table_name, :field_name, :data_type, {}
end
end
There are two good ways to do this:
remove_column
You can simply use remove_column, like so:
remove_column :users, :first_name
This is fine if you only need to make a single change to your schema.
change_table block
You can also do this using a change_table block, like so:
change_table :users do |t|
t.remove :first_name
end
I prefer this as I find it more legible, and you can make several changes at once.
Here's the full list of supported change_table methods:
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table