docs/general/serializers.md in active_model_serializers-0.10.0 vs docs/general/serializers.md in active_model_serializers-0.10.1
- old
+ new
@@ -29,15 +29,26 @@
| In Serializer | #attributes |
|---------------------------- |-------------|
| `attribute :title` | `{ title: 'Some Title' } `
| `attribute :title, key: :name` | `{ name: 'Some Title' } `
-| `attribute :title { 'A Different Title'}` | `{ title: 'A Different Title' } `
+| `attribute(:title) { 'A Different Title'}` | `{ title: 'A Different Title' } `
| `attribute :title`<br>`def title 'A Different Title' end` | `{ title: 'A Different Title' }`
-[PR please for conditional attributes:)](https://github.com/rails-api/active_model_serializers/pull/1403)
+An `if` or `unless` option can make an attribute conditional. It takes a symbol of a method name on the serializer, or a lambda literal.
+e.g.
+
+```ruby
+attribute :private_data, if: :is_current_user?
+attribute :another_private_data, if: -> { scope.admin? }
+
+def is_current_user?
+ object.id == current_user.id
+end
+```
+
### Associations
The interface for associations is, generically:
> `association_type(association_name, options, &block)`
@@ -253,11 +264,11 @@
In the controller, the scope/scope_name options are equal to
the [`serialization_scope`method](https://github.com/rails-api/active_model_serializers/blob/d02cd30fe55a3ea85e1d351b6e039620903c1871/lib/action_controller/serialization.rb#L13-L20),
which is `:current_user`, by default.
-Specfically, the `scope_name` is defaulted to `:current_user`, and may be set as
+Specifically, the `scope_name` is defaulted to `:current_user`, and may be set as
`serialization_scope :view_context`. The `scope` is set to `send(scope_name)` when `scope_name` is
present and the controller responds to `scope_name`.
Thus, in a serializer, the controller provides `current_user` as the
current authorization scope when you call `render :json`.
@@ -366,7 +377,23 @@
```ruby
class PostSerializer < ActiveModel::Serializer
attribute :body do
object.body.downcase
end
+end
+```
+
+## Overriding association serializer lookup
+
+If you want to define a specific serializer lookup for your associations, you can override
+the `ActiveModel::Serializer.serializer_for` method to return a serializer class based on defined conditions.
+
+```ruby
+class MySerializer < ActiveModel::Serializer
+ def self.serializer_for(model, options)
+ return SparseAdminSerializer if model.class == 'Admin'
+ super
+ end
+
+ # the rest of the serializer
end
```