I remember distinctively being in an interview for a job that I didn't get and getting asked if I knew how to access the database to make changes locally. It was my first interview for a rails job and I am pretty sure I didn't answer all the questions to the best of my ability, my response was that I knew to access the Rails console (
rails c
) to adjust and create records in the data. Yesterday it was brought to my attention that you can access the actual db with `rails dbconsole`.Let me outline the issue I had
I created a column on the activities table called reference id. This was planned to hold a stripe reference_id so I can do stuff that is not necessary to explain in this post, just know I needed to save an id that was not already being saved. My issue is that I originally set this column to an integer rather than a string. I was in the need to rollback to the previous migration, which I am well aware of how to do that rake:db:rollback, but I discovered that rather than typing the command repetitively you can write how many steps to go back, like so rails:dbrollback STEP=2 this will take you back 2 migrations.
Knowing how to rollback did not solve my problem. I actually had to adjust my local db, which Postgres. The db "psql" is saved locally on my computer and even though used I rollback I never wrote a down command and caused the column to stick locally, since it was never taught how to delete. I highly recommend using the change method. See below for an example of the using the Down and Change.
The above example would have been great and I would not have had a problem, but with out a down method I basically wrote a bug in migration file and it messed up everything and I could't just change the method cause it was broken.
My resolution was to open up the rails dbconsole which was to actually run the following commands.
ALTER TABLE activities
DROP COLUMN reference_id;
What I did was access the activities table and deleted that specific column. Now with my mistake physically removed from the table I was able to rewrite the migration as a change method and make the column a string as I originally intended.
It is one thing to just blow up the db with a rake db:drop:all and start over, but I have found it takes half a day to recreate my sample data in order to properly test the app, so I try to never do that.
This seems simple, but little things as this are the little tip I continue to learn in my new dev position and I will keep posting them as I learn. If you need more info on this checkout this Stack Overflow.
No comments:
Post a Comment