In Ruby on Rails, there is a scene where you want to write a validation that works only when a certain condition is met, and it took time to solve it, so the following shows how to write a validation that works only when a certain condition is met.
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, when the value of column public_flag (type: integer) of products table is 1, This is an example of imposing a restriction that the column product name (name), product description (description), and product price (price) of the products table cannot be registered if they are empty.
In the following cases, if the value of public_flag is 0, it is possible to register in the products table even if the product name (name), product description (description), and product price (price) values are empty.
model(product.rb)
with_options presence:true, if: :isProductPublicable? do |v|
v.validates :name
v.validates :description
v.validates :price
end
#public_true when flag is 1
def isProductPublicable?
public_flag == 1
end
with_options is an option that allows you to apply multiple validations at once. isProductPublicable? Returns true if the value of column public_flag is 1.
Recommended Posts