mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 15:23:06 +00:00
edits and rearranging logic
This commit is contained in:
30
docs/howto/passing_arbitrary_options.md
Normal file
30
docs/howto/passing_arbitrary_options.md
Normal file
@@ -0,0 +1,30 @@
|
||||
[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
|
||||
```
|
||||
|
||||
Since `user_id` isn't a reserved adapter option, we can process it via a serializer
|
||||
method. The option is passed via the `instance_options` hash.
|
||||
Reference in New Issue
Block a user