rails g model Overall flow

When the environment construction is completed to some extent and it is reflected in the application development, first create the model and table. Here is a brief summary of the basics of creating a model.

Basic flow

① Create model

rails g model [model name] column1: data type, column2: data type, ...

1.Model class file(/app/models/[Model name].rb)
2.Migration file(/db/migrate/yyyyMMddxxxx_create_[table name])
3.Automatic model testing
4.Ficture file used for automatic model testing

② Create / update table

Execute the rails db: migrate command

③ Refer to the table and check if it is created without any problem.

Main points to note in the above flow

① About foreign key constraints

When the references type is set in the foreign key column when executing the rails g model command

There is the following description, so correct it (add)

/db/migrate/yyyyMMddxxxx_create_[table name]


t.references :[Own table name singular]`

/db/migrate/yyyyMMddxxxx_create_[table name]


`t.references :[Own table name singular], foreign_key:true`

Create / update table

If you want to add and set foreign keys for each column later

rails g migration [class name] [reference class name]: references, ... execute the command

Create / update table

Recommended Posts

rails g model Overall flow
[Rails] Model Association (Association)
Model association in Rails
[Rails] Heroku deployment flow
[Rails] gem devise installation flow
Spring Model View Controller Flow
About naming Rails model methods
[Rails] Japaneseize model attribute names
Rails model and table naming conventions
Troublesome Rails environment construction flow [Windows 10]
[Active Admin] rails g active_admin: Create model management screen by resource model name