Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Outside controller use tutorial #1155

Merged
merged 1 commit into from
Sep 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This is the documentation of AMS, it's focused on the **0.10.x version.**

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

## Getting Help

Expand Down
42 changes: 42 additions & 0 deletions docs/howto/outside_controller_use.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
## Using AMS Outside Of A Controller

### Serializing a resource

In AMS versions 0.10 or later, serializing resources outside of the controller context is fairly simple:

```ruby
# Create our resource
post = Post.create(title: "Sample post", body: "I love Active Model Serializers!")

# Optional options parameters
options = {}

# Create a serializable resource instance
serializable_resource = ActiveModel::SerializableResource.new(post, options)

# Convert your resource into json
model_json = serializable_resource.as_json
```

### Retrieving a Resource's Active Model Serializer

If you want to retrieve a serializer for a specific resource, you can do the following:

```ruby
# Create our resource
post = Post.create(title: "Another Example", body: "So much fun.")

# Optional options parameters
options = {}

# Retrieve the default serializer for posts
serializer = ActiveModel::Serializer.serializer_for(post, options)
```

You could also retrieve the serializer via:

```ruby
ActiveModel::SerializableResource.new(post, options).serializer
```

Both approaches will return an instance, if any, of the resource's serializer.