diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb index fac8a207..78930952 100644 --- a/app/controllers/albums_controller.rb +++ b/app/controllers/albums_controller.rb @@ -29,7 +29,7 @@ def create if @album.save render json: transform_album_for_json(@album), status: :created else - render json: @album.errors, status: :unprocessable_entity + render json: transform_errors_for_json(@album.errors.errors), status: :unprocessable_entity end end @@ -37,7 +37,7 @@ def update if @album.update(transformed_attributes) render json: transform_album_for_json(@album), status: :ok else - render json: @album.errors, status: :unprocessable_entity + render json: transform_errors_for_json(@album.errors.errors), status: :unprocessable_entity end end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 35921db4..0a3a2f05 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -27,6 +27,16 @@ def add_pagination_headers(collection) response.headers['Access-Control-Expose-Headers'] = 'x-total-entries, x-total-pages, x-current-page, x-per-page, x-offset' end + def transform_error_for_json(error) + result = %i[attribute type].index_with { |it| error.send(it) } + result[:options] = error.options.except(*ActiveModel::Error::CALLBACKS_OPTIONS, *ActiveModel::Error::MESSAGE_OPTIONS) + result + end + + def transform_errors_for_json(errors) + errors.map { |it| transform_error_for_json(it) } + end + private def authenticate_from_token