如何从spree中删除模型验证

时间:2017-02-17 17:40:36

标签: ruby-on-rails spree

我正在努力解决这个问题超过6个小时。

我想从Spree::Order

中删除验证
module Spree
  class Order < Spree::Base
    MONEY_THRESHOLD  = 100_000_000
    MONEY_VALIDATION = {
      presence:     true,
      numericality: {
        greater_than: -MONEY_THRESHOLD,
        less_than:     MONEY_THRESHOLD,
        allow_blank:   true
      },
      format:       { with: /\A-?\d+(?:\.\d{1,2})?\z/, allow_blank: true }
    }.freeze

    NEGATIVE_MONEY_VALIDATION = MONEY_VALIDATION.deep_dup.tap do |validation|
      validation.fetch(:numericality)[:less_than_or_equal_to] = 0
    end.freeze

    validates :promo_total,          NEGATIVE_MONEY_VALIDATION

    # ...
  end
end

这是我的装饰者

Spree::Order.class_eval do
  # This is not working
  _validators.delete(:promo_total)

  # Nope
  _validators.reject!{ |key, _| key == :promo_total }

  # Nope
  def validate
    errors = self.errors.map {|attr, message| [attr, message]}
    self.errors.clear
    errors.each do |attr, message|
      self.errors.add(attr, message) unless attr == "promo_total"
    end
  end
  # ...
end

当我检查验证时,我收到:promo_total

上的错误
self.valid?
#=> false

self.errors.messages
#=> {:promo_total=>["must be less than or equal to 0"]}

1 个答案:

答案 0 :(得分:1)

你应该试试这个 gem https://github.com/workarea-commerce/active_model-unvalidate

即使是最新版本也应该可以