class JsonApiServer::ValidationErrors

Converts ActiveModel validations to JSON API Errors. Spec: jsonapi.org/format/#error-objects.

Calling render_422(model_instance) in a controller will create an instance of this class and render with appropriate headers.

i.e,

def create
  topic = Topic.new(topic_params)

  if topic.save
   serializer = TopicSerializer.new(topic)
   render json: serializer.to_json, status: :created
 else
   render_422(topic)
 end
end

Public Class Methods

new(model) click to toggle source
# File lib/json_api_server/validation_errors.rb, line 24
def initialize(model)
  errors = get_errors(model)
  @errors = JsonApiServer::Errors.new(errors)
end

Public Instance Methods

as_json() click to toggle source
# File lib/json_api_server/validation_errors.rb, line 29
def as_json
  @errors.as_json
end

Protected Instance Methods

get_errors(model) click to toggle source

Grabs the first error per attribute. Spec -> status: the HTTP status code applicable to this problem, expressed as a string value. jsonapi.org/format/#error-objects

# File lib/json_api_server/validation_errors.rb, line 38
def get_errors(model)
  if model.respond_to?(:errors) && model.errors.respond_to?(:full_messages_for)
    model.errors.keys.map do |field|
      {
        'status' => '422',
        'source' => { 'pointer' => "/data/attributes/#{field}" },
        'title' => 'Invalid Attribute',
        'detail' => model.errors.full_messages_for(field).first
      }
    end
  end
end