【问题标题】:Is there a way to conditionally run rails callbacks only when the model is skipping validations?有没有办法仅在模型跳过验证时有条件地运行 rails 回调?
【发布时间】:2021-07-23 22:02:31
【问题描述】:

当我运行model.save(:validate => false) 时,我想运行一个 before_save 回调,但仅在 validate 为 false 时,而不是在它为 true 时。

我知道您可以有条件地运行如下回调:

class Order < ApplicationRecord
  before_save :normalize_card_number, if: :paid_with_card?
end

但是如何检查:validate =&gt; false 是否被传入?

【问题讨论】:

  • 您可以通过覆盖save 方法来解析参数并将validate: false 值存储在虚拟属性中,然后在before_save all 中检查此属性。但这似乎有点过于复杂,可能是 X-Y 问题。为什么需要在代码中调用validate: false?如果它只在应用程序的一个特定部分,也许您可​​以从那里显式运行回调逻辑(而不是将其挂钩到模型生命周期中)。

标签: ruby-on-rails validation callback


【解决方案1】:

使用@maxpleaner 的评论,您可以通过执行以下操作来实现,

# overwriting the save method to parse the args and store the validate: false value in a virtual attribute (@my_options below)
module ActiveRecord
  module Validations
    def save(**options)
      @my_options = options # => {:validate=>false} in your case
      perform_validations(options) ? super : false
    end
  end
end

class Order < ApplicationRecord
  before_save :normalize_card_number, if: :paid_with_card?
  
  private

  def normalize_card_number
   # using the virtual attribute to solve your problem
    return unless my_options[:validate].eql?(false)
    # Your logic when :validate => false is not passed
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多