I have the model CouponRestriction
, which has the attributes constraint_type
and constraint_value
.
constraint_type
is an integer column (enum
) and I should validate the value of constraint_value
based on the constraint_type
.
For example, if the constraint_type
is "periodicity" I should validate that the constraint_value
is within an array of given values ["monthly", "yearly"]. But if the constraint_type
value is something else, the constraint_value
permitted could be an array of ID's instead of words.
Is there a way to perform such validation depending on the enum column value without writing a custom validation?
I'm trying something like:
validates :constraint_value, inclusion: { in: ["week", "month", "year"] }, if: self.constraint_type == "periodicity"
but I'm getting NoMethodError: undefined method constraint_type for #<Class:0x0000558f3f19c188>
CodePudding user response:
validates :constraint_value,
inclusion: { in: %w(week month year) },
if: -> { constraint_type == "periodicity" }