Skip to content

Commit 25c099e

Browse files
kyreevesshishirmk
authored andcommitted
add documentation for conditional relationships
1 parent 5558dcd commit 25c099e

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ Fast JSON API serialized 250 records in 3.01 ms
3030
* [Collection Serialization](#collection-serialization)
3131
* [Caching](#caching)
3232
* [Params](#params)
33+
* [Conditional Attributes](#conditional-attributes)
34+
* [Conditional Relationships](#conditional-relationships)
3335
* [Contributing](#contributing)
3436

3537

@@ -333,6 +335,27 @@ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }
333335
serializer.serializable_hash
334336
```
335337

338+
### Conditional Relationships
339+
340+
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.
341+
342+
```ruby
343+
class MovieSerializer
344+
include FastJsonapi::ObjectSerializer
345+
346+
# Actors will only be serialized if the record has any associated actors
347+
has_many :actors, if: Proc.new { |record| record.actors.any? }
348+
349+
# Owner will only be serialized if the :admin key of params is true
350+
belongs_to :owner, if: Proc.new { |record, params| params && params[:admin] == true }
351+
end
352+
353+
# ...
354+
current_user = User.find(cookies[:current_user_id])
355+
serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
356+
serializer.serializable_hash
357+
```
358+
336359
### Customizable Options
337360

338361
Option | Purpose | Example

0 commit comments

Comments
 (0)