mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
rough draft
This commit is contained in:
parent
8a040052af
commit
558769981e
46
docs/general/passing_arbitrary_options.md
Normal file
46
docs/general/passing_arbitrary_options.md
Normal file
@ -0,0 +1,46 @@
|
||||
## Passing Arbitrary Options to A Serializer
|
||||
|
||||
Let's say you have a basic Post Controller:
|
||||
|
||||
```
|
||||
class PostController < ApplicationController
|
||||
def dashboard
|
||||
render json: @posts
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
Odds are, your serializer will look something like this:
|
||||
|
||||
```
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
attributes :id, :title, :body
|
||||
end
|
||||
```
|
||||
|
||||
This works all fine and well, but maybe you passing in some "artibrary" options
|
||||
into the serializer. Here's what you would do:
|
||||
|
||||
### posts_controller.rb
|
||||
|
||||
```
|
||||
...
|
||||
def dashboard
|
||||
render json: @posts, user_id: 12
|
||||
end
|
||||
...
|
||||
```
|
||||
|
||||
### posts_serializer.rb
|
||||
|
||||
```
|
||||
...
|
||||
def comments_by_me
|
||||
Comments.where(user_id: instance_options[:user_id], post_id: object.id)
|
||||
end
|
||||
...
|
||||
```
|
||||
|
||||
These options can be anything that isn't already reserved for use by AMS. For example,
|
||||
you won't be able to pass in a `meta` or `root` option like the example above. Those
|
||||
parameters are reserved for specific behavior within the app.
|
||||
Loading…
Reference in New Issue
Block a user