Let's talk about database migrations.
In web applications, we store information in the database. We store the information like in a Excel spreadsheet.
For example, ideas in the Ideator app are stored in the database like this:
Let's say we wanted to also store information about the priority of the idea. For example, it would be nice to be able to tell if the idea is very important or not so important.
We basically want to add a column to the spreadsheet so that we can store information about the priority of the idea like this:
In our rails application, how do we add a new column to the database? We will get back to solving this problem in a bit.
In every Rails application, there is a file called schema.rb
. This file contains information about the all of the database columns in the application.
In your Ideator app, your schema.rb
file should look something like this:
ActiveRecord::Schema.define(version: 2023_12_18_065455) do
create_table "ideas", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t|
t.text "description"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
As you can see, this file contains all of the information about what kind of information we are storing in the application.
For example, if we look at the following:
t.text "description"
t.string "author"
we can see that there is a description
column that is a text
field and an author
column that is a string
field.
Never edit the schema.rb file manually
Since
schema.rb
contains all of the information about the database, it might be tempting to try to edit theschema.rb
file manually when trying to add or change a database column. However, you should never edit theschema.rb
file manually. It won't work and it may cause some bugs.
In order to add or change a database column, you need to run a migration.
For example, in our Ideator app, after we generated the Idea
model, a migration file was also generated as well in this lesson. Migration files are files where you enter information about how you want to update the database. The file looked like this:
class CreateIdeas < ActiveRecord::Migration[6.0]
def change
create_table :ideas do |t|
t.text :description
t.string :author
t.timestamps
end
end
end
To recap, we manually added the following lines into the migration file:
t.text :description
t.string :author
After we created and saved this file, we can run a command called rails db:migrate
, which uses the migration files to update the database columns. It also automatically updates schema.rb
to reflect the new changes, so we don't have to worry about editing schema.rb
.