【问题标题】:How do I stop the others validations to validate when the attribute is not :present in Rails?我如何停止其他验证以验证该属性是否:Rails 中不存在?
【发布时间】:2011-08-26 03:32:20
【问题描述】:

我目前正在做的事情如下:

validates :new_pass,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}

def password_not_blank?
  !new_pass.blank?
end

但这不是 DRY,我敢打赌,如果属性不存在,有一种方法可以跳过验证。

另外,没有任何用于验证的 DSL 方法吗?我认为它比在哈希中实现逻辑更干净......

-- 编辑,谢谢^^--

这是我现在得到的:

validates :new_pass,
          :allow_blank => {:on => :update},
          :presence => {:on => :create},
          :confirmation => true,
          :length => {:within => 6...64}

只是为了记录,所以没有人担心(?),这是一个虚拟属性,实际密码是用 before_save 加密的,检查 :new_pass 不为空。

【问题讨论】:

    标签: ruby-on-rails validation dry dsl skip


    【解决方案1】:

    :allow_nil flag for validates 可能很有趣。像这样的东西应该可以工作:

    validates :new_pass,
              :allow_nil => true,
              :presence => {:if => :new_record?},
              :confirmation => {:if => :password_not_blank?},
              :length => {:within => 6...64, :if => :password_not_blank?}
    

    【讨论】:

    • 谢谢!我认为我需要的是 :allow_blank,因为 :new_pass 可能设置为空字符串。另外,我不需要 :if
    • @Zequez:由于:X_not_blank? 选项的存在,我选择了:allow_nil,但你已经解决了,所以我们都很好。
    【解决方案2】:
    validates :new_pass,:presence => true ,:if => :new_record?
    validates :confirmation ,:length =>:within => 6...64, :if => :password_not_blank?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2014-10-15
      • 2021-07-04
      • 2020-06-04
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多