-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1545 from CodedBeardedSignedTaylor/1506-document-…
…passing-arbitrary-options-to-serializer [DOCS] 1506 document passing arbitrary options to serializer
- Loading branch information
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
[Back to Guides](../README.md) | ||
|
||
# Passing Arbitrary Options To A Serializer | ||
|
||
In addition to the [`serialization_scope`](../general/serializers.md#scope), any options passed to `render` | ||
that are not reserved for the [adapter](../general/rendering.md#adapter_opts) | ||
are available in the serializer as [instance_options](../general/serializers.md#instance_options). | ||
|
||
For example, we could pass in a field, such as `user_id` into our serializer. | ||
|
||
```ruby | ||
# posts_controller.rb | ||
class PostsController < ApplicationController | ||
def dashboard | ||
render json: @post, user_id: 12 | ||
end | ||
end | ||
|
||
# post_serializer.rb | ||
class PostSerializer < ActiveModel::Serializer | ||
attributes :id, :title, :body | ||
|
||
def comments_by_me | ||
Comments.where(user_id: instance_options[:user_id], post_id: object.id) | ||
end | ||
end | ||
``` |