Skip to content

Commit 173f21d

Browse files
author
Terminator3
committed
outside controller use tutorial
1 parent 0c42e32 commit 173f21d

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

docs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ This is the documentation of AMS, it's focused on the **0.10.x version.**
1414

1515
- [How to add root key](howto/add_root_key.md)
1616
- [How to add pagination links](howto/add_pagination_links.md)
17+
- [Using AMS Outside Of Controllers](howto/outside_controller_use.md)
1718

1819
## Getting Help
1920

docs/howto/outside_controller_use.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
## Using AMS Outside Of A Controller
2+
3+
### Serializing a resource
4+
5+
In AMS versions 0.10 or later, serializing resources outside of the controller context is fairly simple:
6+
7+
```ruby
8+
# Create our resource
9+
post = Post.create(title: "Sample post", body: "I love Active Model Serializers!")
10+
11+
# Optional options parameters
12+
options = {}
13+
14+
# Create a serializable resource instance
15+
serializable_resource = ActiveModel::SerializableResource.new(post, options)
16+
17+
# Convert your resource into json
18+
model_json = serializable_resource.as_json
19+
```
20+
21+
### Retrieving a Resource's Active Model Serializer
22+
23+
If you want to retrieve a serializer for a specific resource, you can do the following:
24+
25+
```ruby
26+
# Create our resource
27+
post = Post.create(title: "Another Example", body: "So much fun.")
28+
29+
# Optional options parameters
30+
options = {}
31+
32+
# Retrieve the default serializer for posts
33+
serializer = ActiveModel::Serializer.serializer_for(post, options)
34+
```
35+
36+
You could also retrieve the serializer via:
37+
38+
```ruby
39+
ActiveModel::SerializableResource.new(post, options).serializer
40+
```
41+
42+
Both approaches will return an instance, if any, of the resource's serializer.

0 commit comments

Comments
 (0)