Mic*_*nza 9 validation ruby-on-rails
我希望首先验证字段的存在,如果字段没有值,则返回一条错误消息.然后假设此存在验证通过,我想运行包含验证.
现在我有:
validates :segment_type, presence: true, inclusion: { in: SEGMENT_TYPES }
Run Code Online (Sandbox Code Playgroud)
我尝试将其拆分为两个单独的验证,如下所示:
validates :segment_type, presence: true
validates :segment_type, inclusion: { in: SEGMENT_TYPES }
Run Code Online (Sandbox Code Playgroud)
但问题是上面的两个尝试,当segment_type字段中没有包含任何值时,我得到两个响应的错误消息:
Segment type can't be blank
Segment type is not included in the list
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我只想要"段类型不能为空"而不是第二条消息.
有没有什么方法可以告诉rails进行这种条件验证,并给我所需的错误消息瀑布,而不必定义自定义函数,比如segment_type_presence_and_inclusion_check按顺序检查这些条件并调用它validate :segment_type_presence_and_inclusion_check?
传入选项if内部inclusion以检查是否存在
validates :segment_type,
presence: true,
inclusion: { in: SEGMENT_TYPES, if: :segment_type_present? }
private
def segment_type_present?
segment_type.present?
end
Run Code Online (Sandbox Code Playgroud)
你也可以使用 proc
inclusion: { in: SEGMENT_TYPES, if: proc { |x| x.segment_type.present? } }
Run Code Online (Sandbox Code Playgroud)
您还应该能够使用allow_blank包含验证
validates :segment_type,
presence: true,
inclusion: { in: SEGMENT_TYPES, allow_blank: true }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4179 次 |
| 最近记录: |