What\'s the syntax for dropping a database table column through a Rails migration?
Give below command it will add in migration file on its own
rails g migration RemoveColumnFromModel
After running above command you can check migration file remove_column code must be added there on its own
Then migrate the db
rake db:migrate
first try to create a migration file running the command:
rails g migration RemoveAgeFromUsers age:string
and then on the root directory of the project run the migration running the command:
rails db:migrate
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.
You can try the following:
remove_column :table_name, :column_name
(Official documentation)
Run the following command in your terminal:
rails generate migration remove_fieldname_from_tablename fieldname:fieldtype
Note: the table name should be in plural form as per rails convention.
Example:
In my case I want to remove the accepted
column (a boolean value) from the quotes
table:
rails g migration RemoveAcceptedFromQuotes accepted:boolean
See the documentation re: a convention when adding/removing fields to a table:
There is a special syntactic shortcut to generate migrations that add fields to a table.
rails generate migration add_fieldname_to_tablename fieldname:fieldtype
# db/migrate/20190122035000_remove_accepted_from_quotes.rb
class RemoveAcceptedFromQuotes < ActiveRecord::Migration[5.2]
# with rails 5.2 you don't need to add a separate "up" and "down" method.
def change
remove_column :quotes, :accepted, :boolean
end
end
rake db:migrate
or rails db:migrate
(they're both the same)
....And then you're off to the races!
rails g migration RemoveXColumnFromY column_name:data_type
X = column name
Y = table name
EDIT
Changed RemoveXColumnToY
to RemoveXColumnFromY
as per comments - provides more clarity for what the migration is actually doing.