docs/general/serializers.md in active_model_serializers-0.10.0.rc5 vs docs/general/serializers.md in active_model_serializers-0.10.0
- old
+ new
@@ -36,10 +36,31 @@
[PR please for conditional attributes:)](https://github.com/rails-api/active_model_serializers/pull/1403)
### Associations
+The interface for associations is, generically:
+
+> `association_type(association_name, options, &block)`
+
+Where:
+
+- `association_type` may be `has_one`, `has_many`, `belongs_to`.
+- `association_name` is a method name the serializer calls.
+- optional: `options` may be:
+ - `key:` The name used for the serialized association.
+ - `serializer:`
+ - `if:`
+ - `unless:`
+ - `virtual_value:`
+ - `polymorphic:` defines if polymorphic relation type should be nested in serialized association.
+- optional: `&block` is a context that returns the association's attributes.
+ - prevents `association_name` method from being called.
+ - return value of block is used as the association value.
+ - yields the `serializer` to the block.
+ - `include_data false` prevents the `data` key from being rendered in the JSON API relationship.
+
#### ::has_one
e.g.
```ruby
@@ -53,9 +74,21 @@
def cached_blog
cache_store.fetch("cached_blog:#{object.updated_at}") do
Blog.find(object.blog_id)
end
+end
+```
+
+```ruby
+has_one :blog, if: :show_blog?
+# you can also use a string or lambda
+# has_one :blog, if: 'scope.admin?'
+# has_one :blog, if: -> (serializer) { serializer.scope.admin? }
+# has_one :blog, if: -> { scope.admin? }
+
+def show_blog?
+ scope.admin?
end
```
#### ::has_many