Last active
October 26, 2016 09:04
-
-
Save skliarov/a6fb1f7c6d30759026d4b0cdd89ac2f5 to your computer and use it in GitHub Desktop.
Error serializer for ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ErrorSerializer | |
def ErrorSerializer.serialize(errors) | |
return if errors.nil? | |
new_hash = errors.to_hash(true).map do |k, v| | |
v.map do |msg| | |
{ id: k, title: msg } | |
end | |
end | |
return new_hash.flatten | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
include ErrorSerializer | |
class Api::V1::UsersController < Api::V1::ApiController | |
# POST '/api/v1/user' | |
def create | |
user = User.new(user_params) | |
if user.save | |
user_json = UserSerializer.new(user).attributes.as_json | |
render json: user_json, status: :ok | |
else | |
render json: { errors: ErrorSerializer.serialize(user.errors) }, status: :bad_request | |
end | |
end | |
private | |
def user_params | |
params.require(:user).permit(:first_name, :last_name, :email) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment