首页 > 解决方案 > 自定义 Ruby/rails 模型验证不起作用

问题描述

我为 ruby​​ 模型创建了一个自定义验证(使用 luhn 算法)。即使我明确地false从自定义验证中返回,对象仍然保存。

这就是我的 CreditCard 模型中的内容:

before_save :check_card_number

  private
  def check_card_number
    return false unless card_number_luhn
  end

  def card_number_luhn
     #luhn_algorithm_here_that_returns_true_or_false
  end

但即使我只是返回 false:

before_save :check_card_number

  private
  def check_card_number
    return false
  end

#so this is never even called
  def card_number_luhn
     #luhn_algorithm_here_that_returns_true_or_false
  end

该对象仍然保存。即使我使用validate而不是before_save. 到底是怎么回事?

标签: ruby-on-railsrubyvalidation

解决方案


从 Rails 5 开始,您需要显式调用throw(:abort)

# ...
before_save :check_card_number
# ...
def card_number_luhn
 valid = #luhn_algorithm_here_that_returns_true_or_false
 throw(:abort) unless valid
end

另一种方式:

ActiveSupport.halt_callback_chains_on_return_false = true

参考:https ://www.bigbinary.com/blog/rails-5-does-not-halt-callback-chain-when-false-is-returned


推荐阅读