A memorandum for learning Ruby on Rails. Reference article: Rails guide https://railsguides.jp/active_record_validations.html
Validation is done to save the correct data in the DB. Rails performs validation before saving the object to an ActiveRecord object. If an error occurs there, the object will not be saved. In short, do you meet the storage conditions for DB restrictions? It is a mechanism to check before saving at the DB level.
valid? Can trigger validation manually. Returns true if there are no errors in the saved object Returns false on error.
class User < ApplicationRecord
#Validation(Do not allow empty name)
validates :name, presence: true
end
#This is true(Meet the conditions)
User.create(name: "Gonshiba").valid?
#This is false(Does not meet the condition → name is empty)
User.create(name: "").valid?
invalid? Is a reverse check of valid ?, and only the returned Bool value is reversed. By the way, the create method does everything from object creation to saving.
Recommended Posts