Matheus Silva Matheus Silva - 1 month ago 10
Ruby Question

A field should not be present if according to an enum

I have an enum status:

enum status: [ :x, :y , :z ]


Each status has model attributes that only relate to the selected status.

How would I validate that if the status is 'x' that the attributes related to 'y' and 'z' are blank? And simiar validations are needed for status 'y' and status 'z'.

I want to validate that only the fields (attributes) that relate to the selected status are present.

Answer

You can use the absence in validates

validates :x_attribute, absence: true, if: "status != 'x'"
validates :y_attribute, absence: true, if: "status != 'y'"
validates :z_attribute, absence: true, if: "status != 'z'"

It works for multiple attributes if you want.

validates :x_attribute_1, :x_attribute_2, :x_attribute_3, absence: true, if: "status != 'x'"