-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31_Intro_to_tables_migrations_rails_conventions.txt
More file actions
60 lines (33 loc) · 2.18 KB
/
31_Intro_to_tables_migrations_rails_conventions.txt
File metadata and controls
60 lines (33 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Intro to tables, migrations, rails conventions - text references
-----------------------------------------------------------------------------------
You can take a look at all code-changes made in this video at: https://github.com/udemyrailscourse/alpha-blog-6/commit/05b1ad6dd72231f3d2ea378479d88d4bf68848ad
The additions are shown in green and removals are shown in red.
Details
Model name: article
Class name: Article -> Capitalized A and singular, CamelCase
File name: article.rb -> singular and all lowercase, snake_case
Table name: articles -> plural of model name and all lowercase
Additional example:
Model name: user
Class name: User -> Capitalized U and singular, CamelCase
File name: user.rb -> singular and all lowercase, snake_case
Table name: users -> plural of model name
Generate a migration to create a table (in this example articles):
rails generate migration create_articles
To add attributes for the table in the migration file, add the following inside create_table block:
t.string :title
To run the migration file, run the following command from the terminal:
rails db:migrate
The first time you run the migration file, it will create the database, the articles table and a schema.rb file.
To rollback or undo the changes made by the last migration file that was run, you may use the following command:
rails db:rollback
If you have run the rollback step, then you can update the previous migration file and add the following line to add a description attribute (column) to the articles table:
t.text :description
To run the newly edited migration file again, you can run rails db:migrate
Note: This above line will only work if you had rolled back the prior migration.
To generate a new migration file to add or make changes to your articles table you can generate a new file:
rails generate migration name_of_migration_file
Then within the def change method in the migration file you can add the following lines:
add_column :articles, :created_at, :datetime
add_column :articles, :updated_at, :datetime
You can run the newly created migrations file by running rails db:migrate from the command line and check out the schema.rb file to check that the changes were reflected properly.