导轨:验证一个字段是present只有一个是present [英] Rails: validating a field is present only if another is present

查看:110
本文介绍了导轨:验证一个字段是present只有一个是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? }
 


推荐阅读:


最后,你应该考虑重新命名: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:


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆