我有一个模型,其中有两个字段在技术上可以为空。字段名称是 :is_activated
和 :activated_at
。 :activated_at
仅在 :is_activated
设置为 true
时才需要。如果 :is_activated
为 false
,则不需要存在。在 Rails 中将此验证直接设置到 ActiveRecord 中的合适方法是什么?
最佳答案
您可以使用 Proc在 :activated_at
验证器上。
validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? }
推荐阅读:
- http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
- http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
最后,您应该考虑将 :is_activated
重命名为 :activated
。这在 Rails 中被认为是更好的做法。 is_
前缀在其他语言中用于 bool 属性,因为它们的方法名称不支持 ?
字符。 Ruby 会,而 Rails 会在 bool 属性上生成 ___?
方法。因此,最好只调用属性 :activated
并使用 activated?
检查它。
关于ruby-on-rails - rails : validating a field is present only if another is present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750436/