File: fields.md

package info (click to toggle)
ruby-active-model-serializers 0.10.12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,752 kB
  • sloc: ruby: 13,138; sh: 53; makefile: 6
file content (31 lines) | stat: -rw-r--r-- 796 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.