Skip to content

Commit 1a312bc

Browse files
committed
Merge pull request #1545 from CodedBeardedSignedTaylor/1506-document-passing-arbitrary-options-to-serializer
[DOCS] 1506 document passing arbitrary options to serializer
2 parents 6b4c8df + 48f8a89 commit 1a312bc

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

docs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ This is the documentation of ActiveModelSerializers, it's focused on the **0.10.
2525
- [How to add pagination links](howto/add_pagination_links.md)
2626
- [Using ActiveModelSerializers Outside Of Controllers](howto/outside_controller_use.md)
2727
- [Testing ActiveModelSerializers](howto/test.md)
28+
- [Passing Arbitrary Options](howto/passing_arbitrary_options.md)
2829

2930
## Integrations
3031

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
[Back to Guides](../README.md)
2+
3+
# Passing Arbitrary Options To A Serializer
4+
5+
In addition to the [`serialization_scope`](../general/serializers.md#scope), any options passed to `render`
6+
that are not reserved for the [adapter](../general/rendering.md#adapter_opts)
7+
are available in the serializer as [instance_options](../general/serializers.md#instance_options).
8+
9+
For example, we could pass in a field, such as `user_id` into our serializer.
10+
11+
```ruby
12+
# posts_controller.rb
13+
class PostsController < ApplicationController
14+
def dashboard
15+
render json: @post, user_id: 12
16+
end
17+
end
18+
19+
# post_serializer.rb
20+
class PostSerializer < ActiveModel::Serializer
21+
attributes :id, :title, :body
22+
23+
def comments_by_me
24+
Comments.where(user_id: instance_options[:user_id], post_id: object.id)
25+
end
26+
end
27+
```

0 commit comments

Comments
 (0)