Rails 6 - 创建回调以验证输入的特定文本时出现问题

Rails 6 - issue creating a callback to validate specific text is entered

所以我正在尝试创建一个回调以在保存之前执行快速验证。

我目前正在尝试做的是验证传递给表单隐藏字段的 url 参数未更改并且与三个选项之一完全匹配:

owner_operator、broker_shipper 或运营商

目前我已经试过了,但是,即使参数不匹配其中一个选项,它仍然允许保存表单...

我现在的回调。

accounts.rb

before_validation :validate_account_type

  def validate_account_type
    return if account_type == 'owner_operator' || 'broker_shipper' || 'carrier'
  end

如有任何帮助,我们将不胜感激!

您需要检查 account_type 每个帐户类型文字。

account_type == 'owner_operator' || 'broker_shipper' || 'carrier'

上面的表达式计算如下

(account_type == 'owner_operator') || 'broker_shipper' || 'carrier' 

即使 account_type == 'owner_operator' 的计算结果为 false,表达式中的下一个条件也是 broker_shipper 的计算结果为 true。所以根据条件,您的记录始终有效。

在ruby中,除了nilfalse,其他都是true

所以解决方案是

account_type == 'owner_operator' || account_type == 'broker_shipper' || account_type == 'carrier'

更好

ACCOUNT_TYPES = %w(owner_operator broker_shipper carrier)
def validate_account_type
  ACCOUNT_TYPES.include? account_type
end

了解运算符优先级将对您有帮助运行。