Rails model.valid? flushing custom errors and falsely returning true

前端 未结 5 747
一向
一向 2021-01-07 16:56

I am trying to add a custom error to an instance of my User model, but when I call valid? it is wiping the custom errors and returning true.

[99] pry(main)&g         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 17:07

    create new concerns

    app/models/concerns/static_error.rb

    module StaticError
      extend ActiveSupport::Concern
    
      included do
        validate :check_static_errors
      end
    
      def add_static_error(*args)
        @static_errors = [] if @static_errors.nil?
        @static_errors << args
    
        true
      end
    
      def clear_static_error
        @static_errors = nil
      end
    
      private
    
      def check_static_errors
        @static_errors&.each do |error|
          errors.add(*error)
        end
      end
    end
    

    include the model

    class Model < ApplicationRecord
      include StaticError
    end
    
    model = Model.new
    model.add_static_error(:base, "STATIC ERROR")
    model.valid? #=> false
    model.errors.messages #=> {:base=>["STATIC ERROR"]}
    

提交回复
热议问题