ActiveRecord - replace model validation error with warning

后端 未结 3 1033
滥情空心
滥情空心 2021-02-04 12:51

I want to be able to replace a field error with a warning when saving/updating a model in rails. Basically I want to just write a wrapper around the validation methods that\'ll

3条回答
  •  情深已故
    2021-02-04 13:32

    I don't know if it's ready for Rails 3, but this plugin does what you are looking for:

    http://softvalidations.rubyforge.org/

    Edited to add:

    To update the basic functionality of this with ActiveModel I came up with the following:

    #/config/initializer/soft_validate.rb:
    module ActiveRecord
      class Base
        def warnings
          @warnings ||= ActiveModel::Errors.new(self)
        end
        def complete?
          warnings.clear
          valid?
          warnings.empty?
        end
      end
    end
    
    #/lib/soft_validate_validator.rb
    class SoftValidateValidator < ActiveModel::EachValidator
      def validate(record)
        record.warnings.add_on_blank(attributes, options)
      end
    end
    

    It adds a new Errors like object called warnings and a helper method complete?, and you can add it to a model like so:

    class FollowupReport < ActiveRecord::Base
      validates :suggestions, :soft_validate => true
    end
    

提交回复
热议问题