Since we learned about first_or_initialize, we will output it.
What is first_or_initialize? How to use first_or_initialize?
Describe in the order of.
If the record of the condition searched by where exists, an instance of that record is returned, and if it does not exist, a new instance is created.
It's hard to understand, right? I will explain in detail.
For example Suppose there is a table called student, and each of the 10 names is registered in the database there.
The first_or_initialize method If the student does not exist in the database → Register the student newly. on the other hand, If a student is already registered → Get information about that student.
Did you understand little by little?
That is, the feature of this method is "Avoid duplication of data".
So how do you use it?
student = Student.where(name: "Sato").first_or_initialize
If it doesn't exist, define the object you want to create a new instance of, After that where (condition) .first_or_initialize Then it is completed.
In the above example If Mr. Sato is not in the database → Register the Sato newly. on the other hand, Mr. Sato If you have already registered → Get Mr. Sato's information (defined id, age, etc.).
Recommended Posts