导轨:验证一个字段是present只有一个是present [英] Rails: validating a field is present only if another is present
问题描述
我有一个模型,其中有两个字段,可以从技术上为空。字段名:is_activated
和:activated_at
。 :activated_at
只需要当:is_activated
设置为真
。它并不需要是present如果:is_activated
是假
。什么是Rails中的适当的方式直接设置此验证到的ActiveRecord?
您可以使用的 PROC上的:activated_at
验证
验证:activated_at,:presence,如果: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
简单地:激活
。这被认为是Rails中更好的做法。该是_
preFIX用在其他语言的布尔类型的属性,因为它们的方法名称不支持?
字符。红宝石呢,和Rails生成 ___?
对布尔属性的方法。正因为如此,最好只调用属性:激活
并检查启动
的<?。 / P>
I have a model where there are two fields that can technically be null. The field names are :is_activated
and :activated_at
. :activated_at
is only required if :is_activated
is set to true
. It does not need to be present if :is_activated
is false
. What's the appropriate way in Rails to set this validation directly into ActiveRecord?
You can use a Proc on the :activated_at
validator.
validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? }
Recommended Reading:
- http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
- http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
Finally, you should consider renaming :is_activated
to simply :activated
. This is considered better practice in Rails. The is_
prefix is used in other languages for boolean attributes because their method names don't support a ?
character. Ruby does, and Rails generates ___?
methods on boolean attributes. Because of this it's better to just call the attribute :activated
and check it with activated?
.
这篇关于导轨:验证一个字段是present只有一个是present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!