Add columns to the table
What is a database?
Those that store data. For example, a house. However, if you put all the data at once in your house, it is hard to find out what is where.
What is a table?
Storage location for each type of data. ‥ At home, a room. It is easy to understand and manage by putting it in the relevant place for each type of data. It is called a table.
How to make a table
Name the tables in the database just as you have rooms in your house and each room has its own name.
The database interacts with the model to retrieve and store data. Something like a gatekeeper.
Make a model
- Be in the directory of the app you want to make! % Rails g model model name
The files associated with the model are created.
Invoke active_record create db/migrate/20200315054113_create_posts.rb create app/models/post.rb invoke test_unit create test/models/post_test.rb create test/fixtures/posts.yml
Successful creation with create!
The model file is in app/models/post.rb.
% Rails g model When I named a model, multiple files related to the model were created.
Db/migrate/20200315054113_create_posts.rb (migration file) was created in one of them.
Create the contents of the table with the migration file.
The table was like a room. In addition, we will create types and column names to organize and store the data in it.
If the room is messy, it will be difficult to take out again and it will be difficult to store.
It will be easy to understand as it shows what kind of data will be entered.
integer Numerical value, number of times string Character (short) user name, email address text Character (long text) posted text, explanatory text datetime Date and time Creation date and time, update date and time
As the name implies, it’s a name. You can decide for yourself.
Now, write the column name and type in the migration file.
class CreatePosts <ActiveRecord::Migration[6.0] def change create_table :posts do |t| t.text :memo t.timestamps end end end
t. Column type: Fill in with the column name
I will put many. Describe the column you want to add.
Then, with the Post table in the database. Issue a command to create this column in the table.
Reflect the contents written in the migration file.
% Rails db:migrate *Be in the directory of the app you want to create!
This flow is the basis of the flow of database creation.
- Create a model
- Description of column type and column name in migration file 3.% rails db:migrate