Skip to content

Instantly share code, notes, and snippets.

@csexton
Last active December 17, 2015 17:29
Show Gist options
  • Save csexton/5646709 to your computer and use it in GitHub Desktop.
Save csexton/5646709 to your computer and use it in GitHub Desktop.
Robust JSON

Accept json posts in the following formats:

POST /posts

jsonapi.org plural rooted document:

{"things":[{"name": "My Name", "location": "here"}]}

rails rooted document:

{"thing":{"name":"My Name", "location": "here"}}

top level document:

{"name": "My Name", "location": "here"}

"Be conservative in what you send, be liberal in what you accept" - Robustness Principle

class ThingsController
def update
# ...
@thing.update_attributes(thing_params)
# ...
end
# Use strong params to mangle the incoming json and handle all the different formats
def thing_params
# Adjust the hash for the rooted array:
if params[:thing].empty?
params[:thing] = params[:things].first
end
params.require(:thing).permit :name, :location
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment