[Ruby] Ruby on Rails record search, create if none find_or_create_by method

less than 1 minute read

What is the # find_or_create_by method? The find_or_create_by method is a method that combines the find method and create method. Search the record corresponding to the condition passed in the argument from the table A method that retrieves the corresponding record if it exists and creates it if it does not exist.

How to use

Model.find_or_create_by (search condition)

Example: When the record whose name is “suzuki” is acquired from the users table and is created if there is no such record

User.find_or_create_by(name: "suzuki")