Skip to content

Commit d27b21a

Browse files
luizkowalskiYohan Robert
authored andcommitted
Add docs for the fields option
1 parent bcf3358 commit d27b21a

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Fixes:
1010
- [#1814] (https://github.com/rails-api/active_model_serializers/pull/1814) Ensuring read_multi works with fragment cache
1111

1212
Misc:
13+
- [#1808](https://github.com/rails-api/active_model_serializers/pull/1808) Adds documentation for `fields` option. (@luizkowalski)
1314

1415
### [v0.10.1 (2016-06-16)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0...v0.10.1)
1516

docs/general/fields.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
[Back to Guides](../README.md)
2+
3+
# Fields
4+
5+
If for any reason, you need to restrict the fields returned, you should use `fields` option.
6+
7+
For example, if you have a serializer like this
8+
9+
```ruby
10+
class UserSerializer < ActiveModel::Serializer
11+
attributes :access_token, :first_name, :last_name
12+
end
13+
```
14+
15+
and in a specific controller, you want to return `access_token` only, `fields` will help you:
16+
17+
```ruby
18+
class AnonymousController < ApplicationController
19+
def create
20+
render json: User.create(activation_state: 'anonymous'), fields: [:access_token], status: 201
21+
end
22+
end
23+
```
24+
25+
Note that this is only valid for the `json` and `attributes` adapter. For the `json_api` adapter, you would use
26+
27+
```ruby
28+
render json: @user, fields: { users: [:access_token] }
29+
```
30+
31+
Where `users` is the JSONAPI type.

docs/general/rendering.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,12 @@ See [ARCHITECTURE](../ARCHITECTURE.md) for more information.
7373

7474
#### fields
7575

76-
PR please :)
76+
If you are using `json` or `attributes` adapter
77+
```ruby
78+
render json: @user, fields: [:access_token]
79+
```
80+
81+
See [Fields](fields.md) for more information.
7782

7883
#### adapter
7984

@@ -83,7 +88,7 @@ PR please :)
8388

8489
```render json: posts, each_serializer: PostSerializer, key_transform: :camel_lower```
8590

86-
See [Key Transforms](key_transforms.md) for more informaiton.
91+
See [Key Transforms](key_transforms.md) for more information.
8792

8893
#### meta
8994

0 commit comments

Comments
 (0)