How to drop columns using Rails migration

前端 未结 20 751
执笔经年
执笔经年 2020-12-12 08:50

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

相关标签:
20条回答
  • 2020-12-12 09:28

    Simply, You can remove column

    remove_column :table_name, :column_name
    

    For Example,

    remove_column :posts, :comment
    
    0 讨论(0)
  • 2020-12-12 09:29

    Through
    remove_column :table_name, :column_name
    in a migration file

    You can remove a column directly in a rails console by typing:
    ActiveRecord::Base.remove_column :table_name, :column_name

    0 讨论(0)
  • 2020-12-12 09:32

    Do like this;

    rails g migration RemoveColumnNameFromTables column_name:type

    I.e. rails g migration RemoveTitleFromPosts title:string

    Anyway, Would be better to consider about downtime as well since the ActiveRecord caches database columns at runtime so if you drop a column, it might cause exceptions until your app reboots.

    Ref: Strong migration

    0 讨论(0)
  • 2020-12-12 09:33

    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
    
    0 讨论(0)
  • 2020-12-12 09:35

    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
    
    0 讨论(0)
  • 2020-12-12 09:37

    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 throw an error.

    0 讨论(0)
提交回复
热议问题