我有模型CouponRestriction,它具有屬性constraint_type和constraint_value.
constraint_type是一個整數列 ( enum),我應該constraint_value根據constraint_type.
例如,如果constraint_type是“周期性”,我應該驗證constraint_value是在給定值陣列 ["monthly", "yearly"] 中。但是,如果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>
uj5u.com熱心網友回復:
您需要使用 lambda
validates :constraint_value,
inclusion: { in: %w(week month year) },
if: -> { constraint_type == "periodicity" }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338826.html
