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 }