Glitch in the Matrix Lab
Initialize a new Rails project
- Use
rails new
to make a new Rails project calledmatrix_app_api
- You'll also want to push this homework to your Github Enterprise account; be sure to commit often when prompted.
- Do it now!
Glitch?
- You forgot to use the
--api
flag? Can't really fix that.
Solution: Don't worry about it for now, just keep going!
Glitch?
- You forgot to make postgres the db with the
-d
flag? If you forget this,sqlite
will be the default, and we don't want that. You could fix this by installing thepg
gem and altering thedatabase.yml
file, but since you just made the app it would be easier to start over.
Solution: Delete your folder, do rails new
again, and this time use postgresql.
Commit your work
The commit message should read:
"Commit 1: Initialized Rails server".
Run the Rails server
We haven't done this yet, but in Terminal, run the Rails server with rails s
. The output in Terminal should look like:
In your browser, go to localhost:3000
You should see an error page:
If you remembered to set it up with the --api
flag:
If you forgot the --api
flag:
Glitch!
- The database does not exist
Solution: Quit the server with ctrl + c
. Make the database with rails db:create
Commit your work
The commit message should read:
"Commit 2: Created the db".
Run migrations
Run your migrations with rails db:migrate
.
Glitch!
- Nothing happens. That's because we did not first
generate
any migrations.
Solution: Generate migrations (instructions below)
Generate migrations
We are going to make a table for the database. The table will eventually hold information about characters from the Matrix movies.
Generate a migration to make the table:
rails g migration CreateCharacter
Even though Character is singular, go ahead and press enter to generate the migration.
Glitch!
- I realized that I don't want a table called
character
. I want a table calledcharacters
. It's proper to name the table with a plural of the resource.
Solution: Rails solved this for us automagically!
The migration file should look like this:
You can see that it's going to name the table characters
anyway! Thanks, Rails.
Commit your work
The commit message should read:
"Commit 3: Created table migration".
Give details to migration file
I want my Matrix characters to have a name, description, and image url. All three will be strings. I'm going to try this in the migration file:
I'm going to ignore the fact that I spelled description
wrong (desciption
).
Run migrations
Run the migration to create the table:
rails db:migrate
Glitch!
- When I check the
schema.rb
file, I am disgusted to learn that I spelleddescription
wrong.
Solution: Run another migration to change the column name (instructions below)
Make a corrective migration
I want to change the column in the schema called "desciption" to "description".
- Run a migration
rails g migration FixDescriptionColumnTypo
The migration file should be an empty change method:
Good! No glitches, even though we called our migration FixSomething
rather than ChangeSomething
. It's all good, mates.
Add in rename_column
:
def change
rename_column :characters, :desciption, :description
end
Run the migration
Check migrations
- Check the
schema.rb
file. - Check the db with
rails dbconsole
SELECT * FROM characters;
\q
to quit dbconsole.
Glitch?
- If other columns are not spelled correctly, run more migrations to fix the column names.
Commit your work
The commit message should read:
"Commit 4: Renamed the column".
Change table
Glitch!
I decided I want to name my entire table something other than characters
. I want to call it matrix_characters
because I might add in more movies to my app later, and want to be specific about which movie's characters I'm referencing.
Solution: Create another migration
rails g migration ChangeTableName
I can use a method called rename_table
in the migration file:
class ChangeTableName < ActiveRecord::Migration[6.0]
def change
rename_table :characters, :matrix_characters
end
end
Run the migration
- Check the
schema.rb
Commit your work
The commit message should read:
"Commit 5: Changed table name".
Um, I changed my mind
Glitch!
I don't want the table to be called matrix_characters
. I just want it to be called characters
. I don't want or need the last migration, so can I get rid of it?
Solution:
- Undo the last migration with
rails db:rollback
- Check that the
schema.rb
has "characters" as the table name, not "matrix_characters".
Glitch!
- If I ever run migrations again, it will rename my table again, because that migration file is sitting there ready to go. Ugh! I need to get rid of it!
Solution:
Destroy the migration with rails destroy migration <migration name>
Now the unnecessary migration should be gone. In the future, you could shorten the command to:
rails d migration <migration name>
Commit your work
The commit message should read:
"Commit 6: Rolled back and destroyed migration".
Seed the database
Open the file db/seeds.rb
The pattern for making a single entry is:
Model.create({ column: data, column: data })
Note that the Model name is capitalized and singular.
We can create many of a given Model using an array of entries. Copy this data into your seeds.rb
file, an array of Matrix characters for our Character model (our table is called 'characters', so our model should be called 'Character' ... right?
Character.create([
{ name: "Neo", description: false },
{ name: "Trinity", description: false },
{ name: "Morpheus", description: false },
{ name: "Agent Smith", description: false },
])
To run the seed file:
rails db:seed
Glitch! 👾 Glitch! 👾 Glitch! 👾 Glitch! 👾 Glitch!
- We haven't defined what
Character
is, yet. - Solution: Make a
Character
model to relate to our database (instructions below). Then, we can make ActiveRecord entries for theCharacter
model.
Commit your work
The commit message should read:
"Commit 7: Failed to seed database"
Make a model
To make a model, first we need a model file.
Make a file in app/models
called characters.rb
Can we seed our model yet? Run rails db:seed
Glitch!
- Character is still not recognized
Solution:
- Make a Character class. In
characters.rb
write in:
class Character
end
Can we seed our model yet? Run rails db:seed
.
Glitch!
- Character is still not recognized.
Solution:
- Make the Character class inherit from ApplicationRecord (which, if you look in the
application_record.rb
file, you'll see that it inherits fromActiveRecord
)
class Character < ApplicationRecord
end
Can we seed our model yet? Run rails db:seed
Glitch!
- Nope! Character is still an unrecognized constant.
Solution:
- Rename our model file. Remember, Rails favors convention over configuration. We have to stick to Rails' conventions or we'll be doomed. Rails wants the model files to be singular not plural.
- Rename
characters.rb
tocharacter.rb
.
Can we seed our model yet? Run rails db:seed
.
Glitch?
- There should be no glitch! In fact, there should be nothing printed at all.
If you did get an error, keep trying to fix the glitch.
Check seed data in the db
Open rails dbconsole
SELECT * FROM characters;
Expected output:
If you have any glitches, fix them!
Commit your work
The commit message should read:
"Commit 8: Successfully seeded database"
The seed data is all wrong
Glitch!
- I don't like the seed data. There is an 'f' in the description columns instead of a description, and no data in the imgurl columns. _But if I run more seeds the old data will still be there. I kind of want to reset the whole db with new seed data.
Solution:
- This is kinda overkill, but you never know when you'll need to do this. Drop the databases, run all the migrations all over again and then re-seed the database from scratch. (Instructions below)
Change your seed data to have a (very) brief description
of each Matrix character
Don't worry about the img_url
for now
- Neo on Wikipedia
- Morpheus on Wikipedia
- Trinity on Wikipedia
- Agent Smith on Wikipedia
- Then, run
rails db:reset
Expected output:
reset has dropped the databases, re-run the migrations, and re-seeded the databases.
Check that the db has seeded correctly inside rails dbconsole
SELECT * FROM characters;
\q
to quit
Commit your work
The commit message should read:
"Commit 9: Reset database"
Active Record Queries
Open the Rails console:
rails c
Using Active Record queries, do the following:
- add an
img_url
to each of the Matrix characters - delete Agent Smith
- add a new character: The Oracle
Commit your work
The commit message should read:
"Commit 10: Active Record queries"
Relations
- Make a second model,
vehicles
that has a column forname
andstyle
- Seed a vehicle with a style "Spaceship", and name "Nebuchadnezzar"
- Change the
characters
table to have an integer field calledvehicle_id
- In Rails console, associate Morpheus and Trinity with the Nebuchadnezzar
Commit your work
The commit message should read:
"Commit 11: Relations"
Hungry For More?
- Read through the documentation on Migrations Active Record Migrations
- Read about controllers to prepare you for your next lesson Rails controllers
- Implement an Index route that displays the JSON of all Matrix characters
- Implement a Show route that displays the JSON of a single Matrix character
Commit your work
The commit message should read:
"Commit 12: Implemented controller"