add documentation for conditional relationships

This commit is contained in:
Kyle Reeves 2018-06-26 16:06:33 -05:00 committed by Shishir Kakaraddi
parent 5558dcd703
commit 25c099e923

View File

@ -30,6 +30,8 @@ Fast JSON API serialized 250 records in 3.01 ms
* [Collection Serialization](#collection-serialization)
* [Caching](#caching)
* [Params](#params)
* [Conditional Attributes](#conditional-attributes)
* [Conditional Relationships](#conditional-relationships)
* [Contributing](#contributing)
@ -333,6 +335,27 @@ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }
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
Option | Purpose | Example