diff --git a/CHANGELOG.md b/CHANGELOG.md index 6632cc3f..44e825a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Fixes: - [#1814] (https://github.com/rails-api/active_model_serializers/pull/1814) Ensuring read_multi works with fragment cache Misc: +- [#1808](https://github.com/rails-api/active_model_serializers/pull/1808) Adds documentation for `fields` option. (@luizkowalski) ### [v0.10.1 (2016-06-16)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0...v0.10.1) diff --git a/docs/general/fields.md b/docs/general/fields.md new file mode 100644 index 00000000..a1a12be6 --- /dev/null +++ b/docs/general/fields.md @@ -0,0 +1,31 @@ +[Back to Guides](../README.md) + +# Fields + +If for any reason, you need to restrict the fields returned, you should use `fields` option. + +For example, if you have a serializer like this + +```ruby +class UserSerializer < ActiveModel::Serializer + attributes :access_token, :first_name, :last_name +end +``` + +and in a specific controller, you want to return `access_token` only, `fields` will help you: + +```ruby +class AnonymousController < ApplicationController + def create + render json: User.create(activation_state: 'anonymous'), fields: [:access_token], status: 201 + end +end +``` + +Note that this is only valid for the `json` and `attributes` adapter. For the `json_api` adapter, you would use + +```ruby +render json: @user, fields: { users: [:access_token] } +``` + +Where `users` is the JSONAPI type. diff --git a/docs/general/rendering.md b/docs/general/rendering.md index 35c84958..7237c6a5 100644 --- a/docs/general/rendering.md +++ b/docs/general/rendering.md @@ -73,7 +73,12 @@ See [ARCHITECTURE](../ARCHITECTURE.md) for more information. #### fields -PR please :) +If you are using `json` or `attributes` adapter +```ruby +render json: @user, fields: [:access_token] +``` + +See [Fields](fields.md) for more information. #### adapter @@ -83,7 +88,7 @@ PR please :) ```render json: posts, each_serializer: PostSerializer, key_transform: :camel_lower``` -See [Key Transforms](key_transforms.md) for more informaiton. +See [Key Transforms](key_transforms.md) for more information. #### meta