reform icon indicating copy to clipboard operation
reform copied to clipboard

How do I sync errors back to the model?

Open NullVoxPopuli opened this issue 7 years ago • 4 comments

Complete Description of Issue

I'm trying to render jsonapi formatted errors, via

    def create
      model = resource_proxy.new(create_params)
      form = RegistrationForms::Create.new(model)
      valid = form.validate(create_params)
      form.sync

      if valid && model.save
        render jsonapi: model, status: :created
      else
        render jsonapi: model.errors, status: :unprocessable_entity
      end
    end

I can get form.errors, but it's not the right type of object for the jsonapi renderer to pick up -- which may be an issue I need to take up with active_model_serializers.... but.. not right now.

Is there a built-in way I can sync the errors back to the model?

I suppose I could make some method that

from.errors.each do |field, errors|
  errors.each do |error|
    model.errors.add(field, error)
  end
end

But, am wondering about a built-in way. thanks!

System configuration

Reform version: 2.2.4

NullVoxPopuli avatar May 17 '17 10:05 NullVoxPopuli

This is how I did the sync:

in my api_controller.rb:


  def sync_form_and_model(form, model)
    form.sync

    form_errors = form.errors.messages
    return if form_errors.blank?

    form_errors.each do |field, errors|
      Array[*errors].each do |error|
        model.errors.add(field, error)
      end
    end
  end

I noticed that in master, this api doesn't work. I hope there is something similar for the next release for getting the raw errors hash.

NullVoxPopuli avatar May 18 '17 00:05 NullVoxPopuli

What method is missing when using master, I wonder? The Errors API from ActiveRecord is kinda fuzzy and changes every now and then, so your input is valuable here! :sparkles:

apotonick avatar May 21 '17 21:05 apotonick

@apotonick should we have this as a new feature in the 3.x version?

emaglio avatar Jul 14 '19 17:07 emaglio

With new rails 6.1 it will be much easier: https://code.lulalala.com/2020/0531-1013.html

dmitry avatar Jun 09 '20 11:06 dmitry