File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ ## Passing Arbitrary Options to A Serializer
2+
3+ Let's say you have a basic Post Controller:
4+
5+ ```
6+ class PostController < ApplicationController
7+ def dashboard
8+ render json: @posts
9+ end
10+ end
11+ ```
12+
13+ Odds are, your serializer will look something like this:
14+
15+ ```
16+ class PostSerializer < ActiveModel::Serializer
17+ attributes :id, :title, :body
18+ end
19+ ```
20+
21+ This works all fine and well, but maybe you passing in some "artibrary" options
22+ into the serializer. Here's what you would do:
23+
24+ ### posts_controller.rb
25+
26+ ```
27+ ...
28+ def dashboard
29+ render json: @posts, user_id: 12
30+ end
31+ ...
32+ ```
33+
34+ ### posts_serializer.rb
35+
36+ ```
37+ ...
38+ def comments_by_me
39+ Comments.where(user_id: instance_options[:user_id], post_id: object.id)
40+ end
41+ ...
42+ ```
43+
44+ These options can be anything that isn't already reserved for use by AMS. For example,
45+ you won't be able to pass in a ` meta ` or ` root ` option like the example above. Those
46+ parameters are reserved for specific behavior within the app.
You can’t perform that action at this time.
0 commit comments