reform
reform copied to clipboard
How do I sync errors back to the model?
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
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.
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 should we have this as a new feature in the 3.x version?
With new rails 6.1 it will be much easier: https://code.lulalala.com/2020/0531-1013.html