バリデーションとは
DBにデータが保存される前に、データが正しいか、入力規則に則った形かを確認する仕組みのこと。
create
create!
save
save!
update
update!
バリデーションのスキップ
decrement!
decrement_counter
increment!
increment_counter
toggle!
touch
update_all
update_attribute
update_column
update_columns
update_counters
valid?とinvalid?
valid?とメソッドを組み合わせて使用することでバリデーションが実行され、オブジェクトにエラーがない場合はtrueが返され、そうでなければfalseが返されます invalid?はvalid?と逆の働きをする。 エラーが発生した場合はtrueが返され、そうでなければfalseが返されますよく使いそうなバリデーションヘルパー
errors[]
class Person < ApplicationRecord
validates :name, presence: true
end
>> Person.new.errors[:name].any? # => false
>> Person.create.errors[:name].any? # => true
confirmation
class Person < ApplicationRecord
validates :email, confirmation: true
end
format
class Product < ApplicationRecord
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
message: "英文字のみが使えます" }
end
length
class Person < ApplicationRecord
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
end
属性の長さを検証。
:minimum: 最小値
:maximum: 最大値
:inまたは:within: 値を範囲で指定
属性の長さは与えられた値と等しくないとならない
presence
class Person < ApplicationRecord
validates :name, :login, :email, presence: true
end
指定した属性の値が空でないことを確認。
uniqueness
class Account < ApplicationRecord
validates :email, uniqueness: true
end
属性の値が一意性、重複していないか検証。