[Ruby] What is the right migration data type? ?

2 minute read

What you can do with migration

Table creation Delete table Add column Change column name Change column data type Delete column

Create migration file

The migration file is created when you create the model. It is also possible to create a migration file alone.

terminal


rails g model [model name] [attribute name: data type attribute name: data type...] [option]

# When generating by itself
rails g migration migration name

By executing the above command, a migration file will be created in the db/migrate folder.

What is the right data type? ?

Official Information Rough Overview in Japanese
primary_key primary key
string Character string (1 to 255 characters)
text Long string (1 to 4294967296 characters)
integer integer (4 bytes)
bigint integer (8 bytes)
float floating point
decimal Precision decimal
numeric number
datetime date and time
time time
date date
binary binary data
boolean Boolean type

What to do with something similar but different

Which is more suitable, string or text, when dealing with characters

Since string can handle only up to 255 characters, it is recommended to use text when handling data that may have more than 256 characters depending on the state and time. It is common to handle character information such as names, email addresses, company names, etc. with string, and use text for text information such as text and remarks.

Which is better, string or integer when dealing with enums Since it is an enum that can map the integer of hash, if the column that is planned to be handled by the enum is a string, there is no point in incorporating the enum in the first place, so it doesn’t work. Considering that calmly, integer is suitable for the data type of the column to be handled by enum.

Whether integer or bigint is suitable when dealing with id The id can have a huge number of digits as the number of users increases in the future. Considering that the id column is bigint by default from Rails 5.1, you can basically think that bigint is suitable.

In any case, it is safer to select a larger box if there is a possibility that it will not be in the future in the future, rather than matching the current situation.

Supplement

Rails model naming conventions

In Rails, the table name of the database corresponding to model is plural like members.

However, the class name of model is singular with capital letters like Member.

Also, when creating a model, it is okay to start the member in lowercase like “rails g model member”.

Also, for example, whether you specify member_image or MemberImage, a MemberImage model (table name is member_images) will be created.

However, it is strictly prohibited to use the plural form like members. The Members model will be created. Be sure to create a model in the singular form.

Tags: ,

Updated: