【问题标题】:Rails & Postgres - How do require an either field 1 and field 2 or field 2 and field 3?Rails & Postgres - 如何需要字段 1 和字段 2 或字段 2 和字段 3?
【发布时间】:2016-09-12 13:28:50
【问题描述】:

我正在编写一个从用户输入表单开始的工作应用程序。我很难弄清楚如何让模型验证字段 1 和字段 2 是否有效,或者字段 2 和字段 3 是否有效。这是否超出了 RoR/Postgres 模型应该做的范围?

例如first_name 和 last_name 是必需的,或者 last_name 和birth_date 是必需的。

【问题讨论】:

    标签: ruby-on-rails postgresql validation


    【解决方案1】:

    您可以使用a custom Active Record validation method 执行以下操作:

    class User < ApplicationRecord
      validate :conditional_name_validation
      # ...    
      private
        def conditional_name_validation
          unless (first_name && last_name) ||
                 (last_name && birth_date)
            error = "You must provide either 'first_name' and 'last_name' or 'last_name' and 'birth_date'"
            errors.add(:base, error)
          end
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2021-04-19
      • 2014-07-06
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多