LoginSignup
0
0

More than 1 year has passed since last update.

with_optionsで共通のバリデーションをまとめよう!

Posted at

with_options

「with_options 〇〇 」と書くことで、
複数の情報に対して共通したオプションを付けることが可能となる

記述例

「nickname, last_name, first_name それぞれのカラムが空だと保存できない」というバリデーションを設定する場合

class User < ApplicationRecord
 validates :nickname, presence: true
 validates :last_name, presence: true
 validates :first_name, presence: true
end

上記のようにカラムひとつひとつにpresence: true(カラムが空だと保存できない)というバリデーションを記述することになる

with_options使用した場合

class User < ApplicationRecord
 with_options presence: true do
  validates :nickname
  validates :last_name
  validates :first_name
 end
end

with_options presence:true do 〜 endの記述により、do 〜 endの情報に対して、値が存在 presence しなければならないという制限を一括で設けることができました。

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