我想在驗證中檢查一個整數值。但我想根據另一個欄位的值來做。例如,如果存在寬度值,如果width_type為“px”則至少為300,如果width_type為“rate”則為30。我該怎么做謝謝。
uj5u.com熱心網友回復:
如果我理解正確,您正在尋找條件驗證
在這種情況下,以下應該起作用:
validates :width, numericality: { only_integer: true}
validates :width, numericality: { greater_than_or_equal_to: 300}, if: -> {width_type.to_s == 'px'}
validates :width, numericality: { greater_than_or_equal_to: 30}, if: -> {width_type.to_s == 'rate'}
如果您需要處理太多其他場景,我會使用自定義驗證,例如
MIN_WIDTH_PER_TYPE = {px: 300, rate: 30}
validates :width, numericality: { only_integer: true}
validate :_width_with_type
private
def _width_with_type
min_width = MIN_WIDTH_PER_TYPE[width_type.to_sym]
if width < min_width
errors.add(:width, "must be at least #{min_width} when using width type '#{width_type}'")
end
end
您也可以進一步清理它,但這應該為您指明正確的方向。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503815.html
