开发者

Drop mysql tables in Rails

开发者 https://www.devze.com 2022-12-29 20:14 出处:网络
How do I drop selected tables in Rails? I开发者_高级运维 want to drop all tables from a database with a given prefix. PHPMyAdmin would be very useful at this point.

How do I drop selected tables in Rails? I开发者_高级运维 want to drop all tables from a database with a given prefix. PHPMyAdmin would be very useful at this point.

Thanks


You could install phpMyAdmin and manually delete your tables, or if you wanted to do it from within the rails framework and keep you migrations in sync, why not create a new migration that drops the tables on self.up and creates the tables on self.down.

class DropOldTablesMigration < ActiveRecord::Migration
  def self.up
    drop_table :prefix_table1
    drop_table :prefix_table2
  end

  def self.down
    create_table :prefix_table1 do |t|
      t.column :name, :string
    end
    create_table :prefix_table2 do |t|
      t.column :name, :string
    end
  end
end

EDIT: Just to follow up, if the issue is that there are a lot of tables and you don't want to type them all, you could do something like this:

class DropOldTablesMigration < ActiveRecord::Migration
  def self.up
    ActiveRecord::Base.connection.tables.each do |t|
      unless t.index('yourprefix_') == nil
        drop_table t
      end
    end
  end
end

Of course you would not be able to recreate the tables when you migrate down that way, but depending on what is going on in your app, that may not be a concern.


EDIT IN RESPONSE TO YOUR COMMENT:

To create a new migration, from the root of your app run the following command:

script/generate migration YourMigrationName

The migration file will be created for you in db/migrate. Add the code you want to run and save it. To run the new file enter the following at the command line

rake db:migrate
0

精彩评论

暂无评论...
验证码 换一张
取 消