仅在存在通过时运行rails包含验证

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

jvn*_*ill 9

传入选项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)

  • Rails生成一个方法,其中包含属性+问号的名称,以测试值的存在.所以你可以简单地做`segment_type?`,它与`segment_type.present?`相同 (2认同)

Pau*_*der 8

您还应该能够使用allow_blank包含验证

validates :segment_type,
          presence: true,
          inclusion: { in: SEGMENT_TYPES, allow_blank: true }
Run Code Online (Sandbox Code Playgroud)

  • 这比标记的答案更简单,更优雅.仅供参考'allow_nil:true`.我认为这些是相关的文档:http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates (4认同)