ran*_*its 14 ruby validation activerecord ruby-on-rails
我有一个模型,其中有两个字段在技术上可以为null.字段名称是:is_activated
和:activated_at
.:activated_at
仅在:is_activated
设置为时才需要true
.如果:is_activated
是,则不需要存在false
.Rails将此验证直接设置为ActiveRecord的适当方法是什么?
dee*_*our 35
您可以在验证器上使用Proc:activated_at
.
validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? }
Run Code Online (Sandbox Code Playgroud)
推荐阅读:
最后,您应该考虑:is_activated
简单地重命名:activated
.这在Rails中被认为是更好的做法.该is_
前缀在其他语言中用于布尔属性,因为它们的方法名称不支持?
的字符.Ruby确实如此,Rails ___?
在布尔属性上生成方法.因此,最好只调用属性:activated
并检查它activated?
.
如果您不使用Boolean
属性(例如 )is_activated
,并且希望确保在存在另一个非布尔属性时也存在一个属性,则可以简化它:
validates :activated_at, presence: true, if: :activated_by?
Run Code Online (Sandbox Code Playgroud)
activated_by?
false
将在何时null
以及以其他方式返回true
。