Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: How to drop or remove (join) tables tables from database?

In the Rails 4 documentation (http://guides.rubyonrails.org/migrations.html#creating-a-join-table) I see that to drop a table or a join table, one can use the following methods in command line:

drop_table and drop_join_table.

However, it further adds that one must 'supply a block' -- and I do not know what that looks like in execution.

Regardless here's my question: how do I either drop a table or drop a join table?

Also, when I say drop, I mean remove it from my database. I know I can not delete migrations and that it is not wise to roll back migrations because it messes up collaboration efforts -- so I would like to avoid deleting migration files and rolling back migrations if I can.

I made a mistake when creating migrations to populate the database. I know how to modify the columns of tables (adding new ones, renaming them and deleting them). I just do not know how to purge tables.

Thank you for considering my question.

I would like to remove a table completely from my database. My application is running on Rails 4.

like image 391
robskrob Avatar asked Dec 14 '13 00:12

robskrob


People also ask

How do you delete a table in migration?

First generate an empty migration with any name you'd like. It's important to do it this way since it creates the appropriate date. The only thing I added was drop_table :products and raise ActiveRecord::IrreversibleMigration . Then run rake db:migrate and it'll drop the table for you.

How do you delete a table from schema?

DROP TABLE removes tables from the database. Only the table owner, the schema owner, and superuser can drop a table. To empty a table of rows without destroying the table, use DELETE or TRUNCATE . DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table.


1 Answers

The drop_join_table method is define in document drop_join_table

It takes table 1, table 2 names. Example: you have 2 tables named categories and products, and join table named categories_products)

So create a migration file with any name you like, then you write code to delete join tables: :

def change
  drop_join_table :categories, :products 
end

you can pass in other options to drop_join_table method, these options as the same like create_join_table. Look at this method to see more options.

Example, if your join table does not have name follow convention, like categorization, you could specify it:

def change
  drop_join_table :categories, :products, table_name: categorization 
end

To delete a table, it is simpler with drop_table method:

def change
  drop_table :table_name
end

Others option can be pass in to drop_table method, like options of create_table method

like image 129
Thanh Avatar answered Oct 15 '22 09:10

Thanh