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

前端 未结 5 771
一向
一向 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:17

    This is not a replacement for using the provided validations/framework. However, in some exceptional scenarios, you want to gracefully return an errd model. I would only use this when other alternatives aren't possible. One of the few scenarios I have had to use this approach is inside of a service object creating a model where some portion of the create fails (like resolving a dependent entity). It doesn't make sense for our domain model to be responsible for this type of validation, so we don't store it there (which is why the service object is doing the creation in the first place). However for simplicity of the API design it can be convenient to hang a domain error like 'associated entity foo not found' and return via the normal rails 422/unprocessible entity flow.

    class ModelWithErrors
      def self.new(*errors)
        Module.new do
          define_method(:valid?) { false }
          define_method(:invalid?) { true }
          define_method(:errors) do
            errors.each_slice(2).with_object(ActiveModel::Errors.new(self)) do |(name, message), errs|
              errs.add(name, message)
            end
          end
        end
      end
    end
    

    Use as some_instance.extend(ModelWithErrors.new(:name, "is gibberish", :height, "is nonsense")

提交回复
热议问题