There are times when using jsonapi-resources that you will need to write your own controller actions because you have complicated logic or a resource with relationships to process in a single transactioned request. It's nice to know how to handle the success and failure responses in a JSONAPI compliant manner. Thankfully jsonapi-resources exposes these features to us, you just need to read some code to figure out how to use them.
Consider a use-case where you are updating a Users
model and its collection of assigned Roles
. Say you author an action in your users_controller.rb
named update_user_and_roles
:
def update_user_and_roles
# ... process write your logic to process the `User` model and the `Role` models...that's outside the scope of this example
# render the updated User model in the JSONAPI compliant way
render status: :ok, json: JSONAPI::ResourceSerializer
.new(UserResource, include: ['roles'])
.serialize_to_hash(UserResource.new(user, context))
end
Consider the same update_user_and_roles
example. Perhaps the User
model failed some of its validations and the errors
collection needs to be sent back to the caller in a JSON compliant manner:
def update_user_and_roles
# ... process write your logic to process the `User` model and the `Role` models...that's outside the scope of this example
# render the User model's errors in the JSONAPI compliant way
render status: :unprocessable_entity, json: {
errors: JSONAPI::Exceptions::ValidationErrors.new(User.new(user, context)).errors
}
end