【问题标题】:Rails: validating a field is present only if another is presentRails:仅当另一个字段存在时才验证一个字段是否存在
【发布时间】:2012-12-06 18:49:05
【问题描述】:

我有一个模型,其中有两个字段在技术上可以为空。字段名称为:is_activated:activated_at。仅当 :is_activated 设置为 true 时才需要 :activated_at。如果:is_activatedfalse,则不需要存在。在 Rails 中将此验证直接设置到 ActiveRecord 中的适当方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:

    您可以在:activated_at 验证器上使用Proc

    validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? }
    

    推荐阅读:


    最后,您应该考虑将:is_activated 重命名为简单的:activated。这在 Rails 中被认为是更好的做法。 is_ 前缀在其他语言中用于布尔属性,因为它们的方法名称不支持 ? 字符。 Ruby 可以,Rails 会在布尔属性上生成___? 方法。因此,最好只调用属性:activated 并使用activated? 进行检查。

    【讨论】:

      【解决方案2】:

      非布尔属性。

      如果您没有使用Boolean 属性,例如is_activated,并且希望确保一个属性在另一个非布尔属性存在时存在,您可以简化它:

      validates :activated_at, presence: true, if: :activated_by?
      

      activated_by? 将在nulltrue 否则返回false

      【讨论】:

        【解决方案3】:

        你可以这样做:

        validates :activated_at, presence: true, if: :is_activated?
        
        def is_activated?
          self.is_activated
        end
        

        这只会在 is_activated? 方法返回 true 时验证 :activated_at

        【讨论】:

          猜你喜欢
          • 2021-09-14
          • 2016-01-11
          • 1970-01-01
          • 2011-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多