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:39
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.

查看更多
Animai°情兽
3楼-- · 2019-01-20 21:40

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-20 21:40

Simply, You can remove column

remove_column :table_name, :column_name

For Example,

remove_column :posts, :comment
查看更多
forever°为你锁心
5楼-- · 2019-01-20 21:44

Remove Columns For RAILS 5 App

rails g migration Remove<Anything>From<TableName> [columnName:type]

Command above generate a migration file inside db/migrate directory. Snippet blow is one of remove column from table example generated by Rails generator,

class RemoveAgeFromUsers < ActiveRecord::Migration
  def up
    remove_column :users, :age
  end
  def down
    add_column :users, :age, :integer
  end
end

I also made a quick reference guide for Rails which can be found at here.

查看更多
The star\"
6楼-- · 2019-01-20 21:44

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
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-20 21:45

For removing column from table in just easy 3 steps as follows:

  1. write this command

rails g migration remove_column_from_table_name

after running this command in terminal one file created by this name and time stamp (remove_column from_table_name).

Then go to this file.

  1. inside file you have to write

    remove_column :table_name, :column_name

  2. Finally go to the console and then do

    rake db:migrate

查看更多
登录 后发表回答