自定义ruby/rails模型验证不起作用

lkaoscv7  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(334)

我已经为ruby模型创建了一个自定义验证(使用luhn算法)。即使我刚刚回来 false 从自定义验证中,对象仍然保存。
这就是我的信用卡模型:

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 . 发生了什么事?

zpf6vheq

zpf6vheq1#

在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

相关问题