[Ruby] [Ruby on Rails] Implementation of validation that works only when conditions are met

1 minute read

In Ruby on Rails, there is a scene where I want to write a validation that works only when a certain condition is met, and since it took some time to solve it, the description method of validation that works only when a certain condition is met is shown below.

Overview

Description of validation that is valid only when the value of column X of the record you want to register is a

Concrete example

In the example below, if the value of column public_flag (type: integer) of products table is 1, This is an example in which the constraint that the product name (name), product description (description), and product price (price) values cannot be registered if the values are empty is given.

In the following cases, if the value of public_flag is 0, the product name (name), product description (description), and product price (price) values can be registered in the products table even if they are empty.

  • Public_flag 1: Public information, 0: Private information

model (product.rb)

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

 true when #public_flag is 1
 def isProductPublicable?
  public_flag == 1
 end

▽ with_options is an option that can apply multiple validations collectively. IsProductPublicable? returns true when the value of column public_flag is 1.