[RUBY] Understand migration in rails

Introduction As I was studying Ruby on Rails, I didn't understand various words and concepts related to data manipulation, so I will organize them as a memorandum.

Questions about migration While studying Rails, I had the following questions. Part 1 What are migrations, models, and migration files in the first place? Part 2 When do you migrate? Part 3 What do you create a migration file for?

I will think about each while organizing.

Part 1 What are migrations, models, and migration files in the first place? When manipulating data with Rails, the terms "migration," "model," and "migration file" come up. If you continue studying without understanding the meaning of the terms, you will always come across the question, "What does this mean?" (Me too, I was like that) Therefore, I decided to deepen my understanding of the terms once again.

In a word, it looks like this.

● Model A class that manipulates data. Define for each table </ b> ● Migration Rewrite the table design document </ b> ● Migration file A description of how to rewrite the design document </ b>

Let's take a closer look.

● Model Rails uses a design pattern called MVC. The image looks like an image. ![rails_モデル理解.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/176783/431b7bd3-67fb-8d51-741e-98cc58cab6ab.png)

While each component has its own role, the role of the model is data and business logic. Especially used for database operations. Here is the logic for the operation. In rails, models are defined in the form of classes. Models are created for each table, and operations such as creating and deleting tables are performed through each model. (Image like in a purple balloon)

● Migration The word migration means "migration" in English. And "migration" in Rails means "changing the schema of the table". By the way, the schema is "a design document that determines the outline of the table", so more roughly speaking, migration is "changing the design document of the table" .

● Migration file Rails uses a "migration file" when migrating. In the file, define how you want to change the schema and make the changes based on this file.

Part 2 When do you migrate? From the meaning of the terms organized in Part 1, you can see that the timing of migration is "when changing the table design document". Specifically, creating a table or adding a column. Keep in mind that adding / editing / deleting records does not mean "rewriting the design document itself". Therefore, such an operation is not a migration.

Part 3 What is the migration file created for? Speaking straightforwardly, create it at "timing to perform migration = timing to change the design document of the table".

Saigo ni I've only explained the concept, but it may be hard to get a feel for not actually moving it, including operations in Rails. It's a delicate point whether I can understand myself ... I would like to continue studying.

Recommended Posts