LoginSignup
0
0

More than 1 year has passed since last update.

Rails バリデーション validates

Posted at

バリデーションとは

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
2つのテキストフィールドで受け取る内容が完全に一致する必要がある場合に使用

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: 値を範囲で指定
:flag_is: 属性の長さは与えられた値と等しくないとならない

presence

class Person < ApplicationRecord
  validates :name, :login, :email, presence: true
end

指定した属性の値が空でないことを確認。

uniqueness 

class Account < ApplicationRecord
  validates :email, uniqueness: true
end

属性の値が一意性、重複していないか検証。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0