add documentation for conditional relationships
This commit is contained in:
parent
5558dcd703
commit
25c099e923
23
README.md
23
README.md
@ -30,6 +30,8 @@ Fast JSON API serialized 250 records in 3.01 ms
|
|||||||
* [Collection Serialization](#collection-serialization)
|
* [Collection Serialization](#collection-serialization)
|
||||||
* [Caching](#caching)
|
* [Caching](#caching)
|
||||||
* [Params](#params)
|
* [Params](#params)
|
||||||
|
* [Conditional Attributes](#conditional-attributes)
|
||||||
|
* [Conditional Relationships](#conditional-relationships)
|
||||||
* [Contributing](#contributing)
|
* [Contributing](#contributing)
|
||||||
|
|
||||||
|
|
||||||
@ -333,6 +335,27 @@ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }
|
|||||||
serializer.serializable_hash
|
serializer.serializable_hash
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Conditional Relationships
|
||||||
|
|
||||||
|
Conditional relationships can be defined by passing a Proc to the `if` key. Return `true` if the relationship should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
class MovieSerializer
|
||||||
|
include FastJsonapi::ObjectSerializer
|
||||||
|
|
||||||
|
# Actors will only be serialized if the record has any associated actors
|
||||||
|
has_many :actors, if: Proc.new { |record| record.actors.any? }
|
||||||
|
|
||||||
|
# Owner will only be serialized if the :admin key of params is true
|
||||||
|
belongs_to :owner, if: Proc.new { |record, params| params && params[:admin] == true }
|
||||||
|
end
|
||||||
|
|
||||||
|
# ...
|
||||||
|
current_user = User.find(cookies[:current_user_id])
|
||||||
|
serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
|
||||||
|
serializer.serializable_hash
|
||||||
|
```
|
||||||
|
|
||||||
### Customizable Options
|
### Customizable Options
|
||||||
|
|
||||||
Option | Purpose | Example
|
Option | Purpose | Example
|
||||||
|
Loading…
x
Reference in New Issue
Block a user