【问题标题】:How do you perform conditional validations in Rails of an attribute that depends on another attribute?如何在 Rails 中对依赖于另一个属性的属性执行条件验证?
【发布时间】:2021-02-03 13:14:47
【问题描述】:

我有这个字段 :endpoint,我需要根据另一个属性 (:subscribed_events) 的存在进行不同的验证。

我需要:endpoint 来:

  • 在没有:subscribed_events的情况下允许为空
  • 如果不是nil,则具有有效格式 (http_url)
  • 如果存在:subscribed_events,则存在并使用有效格式 (http_url)

我写过这样的东西:

validates :endpoint, http_url: { allow_blank: true }, presence: true, if: :subscribed_events?

http_url 格式仅在:subscribed_events 存在时才有效,否则它将允许诸如“hello”之类的任何内容。

我可以使http_url 验证不依赖于:subscribed_events 并在一行中验证上述所有条件还是我必须编写不同的验证?

【问题讨论】:

  • 单行写起来听起来很复杂。我会考虑从如何编写一些可以被其他人测试和阅读的内容来解决这个问题,而不是仅仅最大化简洁性。

标签: ruby-on-rails validation conditional-statements


【解决方案1】:

您可以编写自定义验证器。这是您的起点:

validate :endpoint_validator

def endpoint_validator
  unless subscribed_events.blank?
    if endpoint.blank?
      errors.add(:enpoint, "can't be blank if subscribed_events is blank")
      return false
    end
  end

  # http_url validation here
  # other code here

  return true
end

或者,您可以为要自定义验证的每个字段创建一个函数。它实际上更有条理。

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多