您可以根据枚举属性值执行包含验证吗?

Can you perform an inclusion validation based on an enum attribute value?

我有模型 CouponRestriction,它具有属性 constraint_typeconstraint_value

constraint_type 是一个整数列 (enum),我应该根据 constraint_type 验证 constraint_value 的值。

例如,如果 constraint_type"periodicity" 我应该验证 constraint_value 在给定值的数组中 ["monthly" ,“每年”]。但是,如果 constraint_type 值是其他值,则允许的 constraint_value 可以是 ID 数组而不是单词。

有没有一种方法可以在不编写自定义验证的情况下根据枚举列值执行此类验证?

我正在尝试类似的东西:

validates :constraint_value, inclusion: { in: ["week", "month", "year"] }, if: self.constraint_type == "periodicity"

但我得到 NoMethodError: undefined method constraint_type for #<Class:0x0000558f3f19c188>

You need to use a lambda

validates :constraint_value, 
          inclusion: { in: %w(week month year) }, 
          if: -> { constraint_type == "periodicity" }