[Rails] first_or_initialize

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.

What is first_or_initialize?

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?

How to use first_or_initialize


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

[Rails] first_or_initialize
[Rails g.error]
Rails basics
Rails Review 1
Rails API
Rails migration
rails tutorial
About Rails 6
Rails foundation
Rails memorandum
rails tutorial
rails tutorial
rails tutorial
[Rails] devise
rails tutorial
rails tutorial
Rails Tips
rails method
rails tutorial
[Rails] ActiveRecord
[Rails] form_with
Rails Review 2
Rails CSV basics
Rails6 jQuery introduced
About Rails routing
Rails Routing Basics
Add binding.pry (rails)
Rails access restrictions
Rails and FormData
rails tutorial Chapter 6
Rails tutorial test
Rails render redirect_to
[Rails] Favorite feature
Rails Bootstrap introduced
[Rails] Many-to-many creation
[Rails] Naming convention
Rails Credentials Note
Rails Logger Basics
[Rails] Introducing jquery
[Rails 6] Ranking function
Rails Flash Message
Tailwind on Rails
rails tutorial Chapter 1
Rails delegate method
[Rails 6] cocoon_ introduction
[Rails] Introduce Carrierwave
Rails tutorial memorandum 1
[rails] Set validation
Rails learning day 3
Rails tutorial memorandum 2
Rails learning day 4
Implement Rails pagination
[Rails] Category function
rails tutorial Chapter 7
[Rails] Introducing devise
rails tutorial Chapter 5
Group_by in Rails
Rails follow function
rails tutorial Chapter 10
Rails 6.0 Routing Summary
[Rails] Extend UrlHelper