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.
Description of validation that is valid only when the value of column X of the record you want to register is a
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
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.