0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-06 13:08:40 +08:00
discourse/lib/service/base/model_step.rb
Martin Brennan ea74b65aa5
DEV: Preserve existing errors in service model steps (#41896)
`ModelStep` revalidates changed models by calling `invalid?`, which
clears errors
added by the model producer before validations run. For example,
`UploadCreator`
can return an unsaved `Upload` containing an image-processing error;
`ModelStep`
then clears that error and may treat the `Upload` as valid.

Treat models that already contain errors as invalid without revalidating
them.
This preserves operation-specific errors for `on_model_errors` while
continuing
to validate changed models that do not already contain errors.

---------

Co-authored-by: Loïc Guitaut <loic@discourse.org>
2026-07-23 17:15:26 +10:00

36 lines
953 B
Ruby
Vendored

# frozen_string_literal: true
module Service
module Base
# @!visibility private
class ModelStep < Step
class NotFound < StandardError
end
attr_reader :optional
def initialize(name, method_name = name, class_name: nil, optional: nil)
super(name, method_name, class_name: class_name)
@optional = optional.present?
end
def run_step
model = context[name] = super
raise NotFound if !optional && (!model || model.try(:empty?))
if model.try(:has_changes_to_save?) && (model.errors.present? || model.invalid?)
context[result_key].fail(invalid: true)
context.fail!
end
rescue Failure, DefaultValuesNotAllowed
raise
rescue => exception
context[result_key].fail(
not_found: true,
exception: (exception unless exception.is_a?(NotFound)),
)
context.fail!
end
end
end
end