first_name
and last_name
. I could use this shortcut from the Command Line:g
is short for generate
, the same way s
is short for server
and c
is short for console
.app/models
named Instructor
, and made it inherit database-related superpowers from ActiveRecord::Base
.db/migrate
, and added instructions to it to create a table called instructors
, with the columns/datatypes that we specified after the model's name.
Aside: Making Changes To Your DatabaseWe have a few tools to make changes to our database once we have already run our migrations.First and foremost, we can generate new migrations to add new tables and modify existing tables. To modify existing tables, the most common tools we use areadd_column
andremove_column
.Simply generate a new migration (not a whole model like above) like1rails g migration AddTitleToInstructorsCopied!or1rails g migration RemoveLastNameFromInstructorsCopied!Then, go into the new migration file and add instructions to make the change you want within thechange
method (or theup
method, if that's what you find inside instead ofchange
):1def change2add_column :instructors, :title, :string3remove_column :instructors, :last_name4endCopied!Then execute the instructions withrails db:migrate
.If your database gets into a weird state (usually caused by deleting old migration files), your ultimate last resort is1rails db:dropCopied!This will destroy your entire database and all the data within it. Then, you can re-run all your migrations from scratch after fixing them to be however you like.Much more information about migrations can be found at the official Rails Guide:
rails console
from within the root folder of your application.i
and it should show you that i
has been inserted into the database and it has been assigned an ID number..each
, .count
, etc.YourModel.find_by()
method needs to know the { :column => "criteria" }
to lookup by..find_by
or .find
methods as described above..where
. The .where
method will always return an ActiveRecord Collection of results, whether there are zero matches, one match, or a thousand matches. It's up to you, then, to pull each row out of the collection and do whatever you need to with it; exactly as you do after .all
..where
can be used to look stuff up just like .find_by
, if we provide a list of columns and criteria that we want to match within a hash:.where
can also be used to search for partial matches by passing a fragment of SQL in a string, rather than passing a hash:%
are wildcard characters, which match anything in that position.(1..4)
is 1, 2, 3, and 4; (1...4)
is only 1, 2, and 3..where
; it will then bring back the rows that match ANY of the criteria for that column:.pluck
: