0
0

More than 3 years have passed since last update.

【Ruby on Rails】条件合致する時のみ機能するバリデーションの実装

Last updated at Posted at 2020-08-23

Ruby on Railsにおいて、ある条件に合致する時のみ機能するバリデーションを記述したい場面があり、解決するまでに時間がかかったため、ある条件に合致する時のみ機能するバリデーションの記述方法を下記に示します。

概要

登録したいレコードのカラムXの値がaの時のみ有効になるバリデーションの記述

具体例

下記例は、products tableのカラムpublic_flag(型:integer)の値が1の場合、
products tableのカラム商品名(name)、商品説明(description)、商品価格(price)の値が空では登録できないという制約を付与している例である。

下記の場合、public_flagの値が0の場合、商品名(name)、商品説明(description)、商品価格(price)の値が空でもproducts tableへ登録が可能である。
 ※public_flag 1: 公開情報、0: 非公開情報

model(product.rb)

 with_options presence:true, if: :isProductPublicable?  do |v|
   v.validates :name
   v.validates :description
   v.validates :price
 end

 #public_flagが1の時 true
 def isProductPublicable?
  public_flag == 1
 end

 
 with_optionsは複数のバリデーションをまとめてかけることができるオプションである。
 isProductPublicable?はカラムpublic_flagの値が1の場合、trueを返却する。

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