Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I sync errors back to the model? #432

Open
NullVoxPopuli opened this issue May 17, 2017 · 4 comments
Open

How do I sync errors back to the model? #432

NullVoxPopuli opened this issue May 17, 2017 · 4 comments
Milestone

Comments

@NullVoxPopuli
Copy link

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
Copy link
Author

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.

@apotonick
Copy link
Member

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! ✨

@emaglio emaglio added this to the 3.0 milestone Jul 14, 2019
@emaglio
Copy link
Member

emaglio commented Jul 14, 2019

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

@dmitry
Copy link

dmitry commented Jun 9, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants