【发布时间】:2015-06-05 15:02:04
【问题描述】:
我想先验证一个字段是否存在,如果该字段没有值,则返回一条错误消息。然后假设此存在验证通过,我想运行包含验证。
现在我有:
validates :segment_type, presence: true, inclusion: { in: SEGMENT_TYPES }
我已尝试将其拆分为两个单独的验证,如下所示:
validates :segment_type, presence: true
validates :segment_type, inclusion: { in: SEGMENT_TYPES }
但问题在于上述两种尝试,当segment_type 字段中不包含任何值时,我都会收到两种响应的错误消息:
Segment type can't be blank
Segment type is not included in the list
在这种情况下,我只想要“Segment type can't be blank”而不是第二条消息。
有没有什么方法可以告诉 Rails 执行此条件验证并给我所需的错误消息瀑布,而无需我定义一个自定义函数,例如 segment_type_presence_and_inclusion_check,它依次检查这些条件并使用 @ 调用它987654326@?
【问题讨论】: