How to drop columns using Rails migration

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

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

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

    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

    0 讨论(0)
  • 2020-12-12 09:22
    remove_column :table_name, :column_name
    

    For instance:

    remove_column :users, :hobby
    

    would remove the hobby Column from the users table.

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

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

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

    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.

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

    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

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