Simple JSON:API compliant parameters translator.
Add this line to your application's Gemfile:
gem'jsonapi_parameters'And then execute:
$ bundleOr install it yourself as:
$ gem install jsonapi_parametersUsually your strong parameters in controller are invoked this way:
defcreatemodel=Model.new(create_params)ifmodel.save
...
elsehead500endendprivatedefcreate_paramsparams.require(:model).permit(:name)endWith jsonapi_parameters, the difference is just the params:
defcreate_paramsparams.from_jsonapi.require(:model).permit(:name)endJsonApi::Parameters supports ActiveRecord relationship parameters, including nested attributes.
Relationship parameters are being read from two optional trees:
relationships,included
If you provide any related resources in the relationships table, this gem will also look for corresponding, included resources and their attributes. Thanks to that this gem supports nested attributes, and will try to translate these included resources and pass them along.
For more examples take a look at Relationships in the wiki documentation.
params={# JSON:API compliant parameters here# ...}classTranslatorincludeJsonApi::Parametersendtranslator=Translator.newtranslator.jsonapify(params)As stated in the JSON:API specification correct mime type for JSON:API input should be application/vnd.api+json.
This gem's intention is to make input consumption as easy as possible. Hence, it registers this mime type for you.
In theory, any payload may consist of infinite amount of relationships (and so each relationship may have its own, included, infinite amount of nested relationships). Because of that, it is a potential vector of attack.
For this reason we have introduced a default limit of stack levels that JsonApi::Parameters will go down through while parsing the payloads.
This default limit is 3, and can be overwritten by specifying the custom limit.
classTranslatorincludeJsonApi::Parametersendtranslator=Translator.newtranslator.jsonapify(custom_stack_limit: 4)# ORtranslator.stack_limit=4translator.jsonapify.(...)defcreate_paramsparams.from_jsonapi(custom_stack_limit: 4).require(:user).permit(entities_attributes: {subentities_attributes: { ... }})end# ORdefcreate_paramsparams.stack_level=4params.from_jsonapi.require(:user).permit(entities_attributes: {subentities_attributes: { ... }})ensureparams.reset_stack_limit!endIf you need custom relationship handling (for instance, if you have a relationship named scissors that is plural, but it actually is a single entity), you can use Handlers to define appropriate behaviour.
Read more at Relationship Handlers.
Project started by Jasiek Matusz.
Currently, jsonapi_parameters is maintained by Visuality's Open Source Commitee.
The gem is available as open source under the terms of the MIT License.