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を返却する。