goals do
goal "Create a table in the database for jobs"
goal "Review what a database is"
goal "Learn what a migration file is"
end
discussion_box "Databases & SQL",
<<-MARKDOWN
Review how relational databases are structured, how we communicate with them?
* How do you read data from a Database with SQL?
* How do you read data from a Database with ActiveRecord?
MARKDOWN
steps do
step "generate a jobs model and a jobs migration" do
message <<-MARKDOWN
In order to make it possible for users to create jobs,
* we need a place to store the jobs (a table in the database)
* we need Rails to know what a job is (a model)
We're going to use another Rails generator; this time to make our migration and model!
MARKDOWN
console "rails g model job"
message <<-MARKDOWN
(The g stands for *generate*, which has many more letters than is necessary to type.)
That generated two files: a migration and models/job.rb.
Find the migration file in your editor!
MARKDOWN
end
step "add columns to the migration" do
message "Open up the migration file and you'll see the following:"
source_code :ruby, <<-RUBY
class CreateJobs < ActiveRecord::Migration[5.0]
def change
create_table :jobs do |t|
t.timestamps
end
end
end
RUBY
message <<-MARKDOWN
Running this code will make a table in our database called jobs.
Right now it just has the timestamps (`created_at` and `updated_at`),
and the id as a primary key, because we did not specify any
columns when we generated it.
What else should a job have? Let's start with a title and description.
Add the title and description so the migration file looks like this:
MARKDOWN
source_code :ruby, <<-RUBY
create_table :jobs do |t|
t.string :title
t.text :description
t.timestamps
end
RUBY
end
step "create the table in the database" do
message "Now we need to execute the migration file, so that the database schema gets updated."
console "rails db:migrate"
message <<-MARKDOWN
This tells Rails to run any migration files that haven't already been run at some point in the past.
MARKDOWN
discussion_box "Why do we use migrations?",
<<-MARKDOWN
Talk about the pros and cons of using migrations to update the database, instead of just updating the schema directly. Also, discuss what the database schema is!
(Pro-tip: *never* update the schema directly.)
MARKDOWN
end
step "Check out the model" do
message "The migration we just ran updated the database, but that doesn't mean that we can talk to the database using Ruby yet. Look at the file `app/models/job.rb`."
message "The model is empty right now, but it will know how to talk to the database, and will know about the columns in the database, because it inherits from `ApplicationRecord`"
end
end
commitnow
next_step "add_a_new_job_form"