You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can take advantage of the scope to customize the objects returned based
180
+
on the current user (scope).
181
+
182
+
For example, we can limit the posts the current user sees to those they created:
183
+
184
+
```ruby
185
+
class PostSerializer < ActiveModel::Serializer
186
+
attributes :id, :title, :body
187
+
188
+
# scope comments to those created_by the current user
189
+
has_many :comments do
190
+
object.comments.where(created_by: current_user)
191
+
end
192
+
end
193
+
```
194
+
195
+
Whether you write the method as above or as `object.comments.where(created_by: scope)`
196
+
is a matter of preference (assuming `scope_name` has been set).
197
+
198
+
##### Controller Authorization Context
199
+
200
+
In the controller, the scope/scope_name options are equal to
201
+
the [`serialization_scope`method](https://github.com/rails-api/active_model_serializers/blob/d02cd30fe55a3ea85e1d351b6e039620903c1871/lib/action_controller/serialization.rb#L13-L20),
202
+
which is `:current_user`, by default.
203
+
204
+
Specfically, the `scope_name` is defaulted to `:current_user`, and may be set as
205
+
`serialization_scope :view_context`. The `scope` is set to `send(scope_name)` when `scope_name` is
206
+
present and the controller responds to `scope_name`.
207
+
208
+
Thus, in a serializer, the controller provides `current_user` as the
209
+
current authorization scope when you call `render :json`.
210
+
211
+
**IMPORTANT**: Since the scope is set at render, you may want to customize it so that `current_user` isn't
212
+
called on every request. This was [also a problem](https://github.com/rails-api/active_model_serializers/pull/1252#issuecomment-159810477)
213
+
in [`0.9`](https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope).
214
+
215
+
We can change the scope from `current_user` to `view_context`.
0 commit comments