Ctrl+Z in Rails 5: Undo Tables, Models, and Controllers

url: https://medium.com/@limichelle21/ctrl-z-in-rails-5-undo-tables-models-and-controllers-bc012ca49d68


 

I recently had to redo parts of my database which involved dropping a table, a model, a controller, and the associated files. I could go through every file in my directory and delete them one by one, but 1) that would take time and 2) would result in high likelihood that I’d miss a spec file. Luckily, there’s commands for people like me who start out in one direction and then change their mind, requiring a re-do.

Assuming this model has been living in the app for quite some time, three things need to happen:

Remove the Table from the Schema

Create a Rails migration and use the following code:

def change
drop_table(:model_name)
end

I ran the above migration as is, expecting any indexes on other tables related to this table to also be removed. Upon closer inspection of my schema, it appears this wasn’t the case. So I ran another migration to remove any reference of model_id from my other tables.

def change
remove_column :table_name1, :column_to_be_removed, :datatype
remove_column :table_name2, :column_to_be_removed, :datatype
end

The two separate migrations can be combined into one to achieve the same result. Now that my schema looked correct, I needed to remove the associated code with the deleted table.

Delete the Model

Run the opposite command of a rails generate model to remove all of the files associated with a model (specs, factories, etc).

rails destroy model Model_name

Delete the Controller + Views

Run the opposite command of rails generate controller to remove all of the files associated with a controller (specs, helpers, views directory, javascript + CSS files).

rails destroy controller controller_name

The short hand syntax for both commands above are:

rails d model Model_name
rails d controller controller_name

I didn’t find any commands related to removing any/all references to the table from other locations (such as another model.rb file that references a has_many relationship). Running a ctrl+F for the deleted model name on the entire directory should bring you to every location in which you’d need to update the code.

For more immediate Ctrl+Z issues, such as trying to undo a migration that just happened, use the following command to fix the schema:

rake db:rollback

And that’s it! Sometimes the fixes are actually simple.

 

posted @ 2018-08-14 18:40  柠檬雨  阅读(54)  评论(0)    收藏  举报