From 021e12d36b818683e66dd41fedc1a8dddf856e6b Mon Sep 17 00:00:00 2001 From: opsb Date: Thu, 31 Jul 2014 11:30:36 -0500 Subject: [PATCH] Add documentation to for the ActiveModelAdapter --- data/guides.yml | 2 + .../guides/models/the-active-model-adapter.md | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 source/guides/models/the-active-model-adapter.md diff --git a/data/guides.yml b/data/guides.yml index ba48b08593..97b025d882 100644 --- a/data/guides.yml +++ b/data/guides.yml @@ -203,6 +203,8 @@ Models: url: "models/connecting-to-an-http-server" - title: "Handling Metadata" url: "models/handling-metadata" + - title: "The Active Model Adapter" + url: "models/the-active-model-adapter" - title: "Customizing Adapters" url: "models/customizing-adapters" - title: "Frequently Asked Questions" diff --git a/source/guides/models/the-active-model-adapter.md b/source/guides/models/the-active-model-adapter.md new file mode 100644 index 0000000000..eaed5b2296 --- /dev/null +++ b/source/guides/models/the-active-model-adapter.md @@ -0,0 +1,70 @@ +Ember comes with great support for integrating with rails' active-model-serializers. + +## Setup + +### Ember +You need to tell ember to use both the ActiveModelAdapter and the ActiveModelSerializer. + +```js +App.ApplicationAdapter = DS.ActiveModelAdapter.extend({ + +}); + +App.ApplicationSerializer = DS.ActiveModelSerializer.extend(App.EmbeddedRecordsMixin, { + +}); +``` + +### Rails +In your serializers you need to specify couple of options: + +```ruby +class ArchiveSerializer < ActiveModel::Serializer + embed :ids, include: true + ... +end +``` + +These tell active-model-serializers to generate json in the format that the ember adapter expects. + + +## Serializing relationships from ember +By default the ActiveModelAdapter won't try to serialize any relationships. To tell it to include relationships you need to specify how they should be serialized. + +Assuming the following models: + +```js +App.Author = DS.Model.extend({ + name: DS.attr("string"), + books: DS.hasMany('book') +}); + +App.Book = DS.Model.extend({ + name: DS.attr("string"), + author: DS.belongsTo('author') +}); +``` + +Let's tell the ActiveModelAdapter how to serialize an author + +```js +App.AuthorSerializer = DS.ActiveModelSerializer.extend(App.EmbeddedRecordsMixin, { + attrs: { + books: { embedded: 'always' } + } +}); + +``` +The embedded: 'always' tells ember to serialize the books relationship whenever an author is saved. The json for serializing an author matches the rails conventions: + +```js +{ + author: { + name: "William Shakespeare" + books_attributes: [ + { name: "Macbeth" }, + { name: "Richard III" } + ] + } +} +```