Search code examples
ruby-on-rails-4rails-migrationsdrop-table

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.


Solution

  • 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