How to drop columns using Rails migration

2019-01-20 20:56发布

What's the syntax for dropping a database table column through a Rails migration?

17条回答
老娘就宠你
2楼-- · 2019-01-20 21:47

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
查看更多
别忘想泡老子
3楼-- · 2019-01-20 21:48

To remove the column from table you have to run following migration:

rails g migration remove_column_name_from_table_name column_name:data_type

Then run command:

rake db:migrate
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-20 21:49

in rails 5 you can use this command in the terminal:

rails generate migration remove_COLUMNNAME_from_TABLENAME COLUMNNAME:DATATYPE

for example to remove the column access_level(string) from table users:

rails generate migration remove_access_level_from_users access_level:string

and then run:

rake db:migrate
查看更多
贼婆χ
5楼-- · 2019-01-20 21:49

Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

remove_column :users, :last_name, :string

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will error.

查看更多
Root(大扎)
6楼-- · 2019-01-20 21:50

You can try the following:

remove_column :table_name, :column_name

(Official documentation)

查看更多
登录 后发表回答