简体   繁体   中英

Drop all columns from table in Rails migration

Say in Rails 3, you have a model User and hence its table is called :users

Something went horribly wrong and you need to drop the table but you cannot since you have other references to the user_id . So you need to clear your users table schema.

Basically what you need is a way to drop all columns.

If your table has more than 40 columns, you can forget the style

remove_column :users, :col1

You need to do it all at once. In one migration

Assuming you have generated a blank migration using

rails g migration PurgeOldUsersSchema

So this is how your migration should look like

class PurgeOldUsersSchema < ActiveRecord::Migration
  def change
    cols = []
    User.columns.collect(&:name).each do |col|
     cols.push(col.to_sym)
    end
    cols = cols - [:id]
    remove_column :users, cols
  end
end

Keep in mind the - [:id] is necessary since rails cannot allow you to drop the primary key. In this array you can add any column name you want to preserve post the purge op.

This keeps your references to this table intact in the schema, but you would anyway purge the data, so that is not much relevant. :-)

UPDATE

Have tried this solution but remove_column :users, cols didn't work for me so I had to replace it with:

cols.each { |col| remove_column :users, col }

Run rake db:migrate:down VERSION=XXX in the terminal and it should remove all data on the Users table.

And then run: rake db:migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM