LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】validationの冗長をなくす方法

Last updated at Posted at 2023-02-15

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

背景

全てのカラムに対して同じバリデーションを設定すると、下記のように同じ記述が繰り返され冗長性がある状態である。

User.rb
class User < ActiveRecord::Base
  validates :name, presence: true       #冗長性あり
  validates :email,  presence: true     #冗長性あり
  validates :age,  presence: true       #冗長性あり
  validates :password,  presence: true  #冗長性あり
end

やりたいこと

バリデーションの冗長性をなくしたい。

方法

with_optionsブロックを使う

下記のようにwith_optionsブロックでpresenceをまとめることで、ブロック内のカラムすべてに適用されるようになる。

User.rb
class User < ActiveRecord::Base
  with_options presence: true do
    validates :name
    validates :email
    validates :age
    validates :password
  end
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