How to drop columns using Rails migration

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

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

20条回答
  •  再見小時候
    2020-12-12 09:45

    Clear & Simple Instructions for Rails 5 & 6

    • WARNING: You will lose data if you remove a column from your database. To proceed, see below:
    • Warning: the below instructions are for trivial migrations. For complex migrations with e.g. millions and millions of rows, you will have to account for the possibility of failures, you will also have to think about how to optimise your migrations so that they run swiftly, and the possibility that users will use your app while the migration process is occurring. If you have multiple databases, or if anything is remotely complicated, then don't blame me if anything goes wrong!

    1. Create a migration

    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

    2. Check the migration

    # 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
    

    3. Run the migration

    rake db:migrate or rails db:migrate (they're both the same)

    ....And then you're off to the races!

提交回复
热议问题