I'm fairly new to EmberJS, and I've been fiddling around for most of the evening trying to persist some hasMany and many to many relationships in a new app that I'm working on.
I'm using Ember Data with ActiveModelAdapter
to hook it up to my rails backend which is using ActiveModelSerializers
I'm using the following versions of Ember and Ember Data that I'm using.
DEBUG: -------------------------------
DEBUG: Ember : 1.6.0-beta.1+canary.d0f5f254
DEBUG: Ember Data : 1.0.0-beta.7+canary.d5562867
DEBUG: Handlebars : 1.1.1
DEBUG: jQuery : 1.10.2
DEBUG: -------------------------------
The basic problem I've been having is that when saving records, the association ids aren't being sent back to the server.
I took a dive into the ActiveModelSerializer source, and found that it skips hasMany serialization
var ActiveModelSerializer = RESTSerializer.extend({ // ...
/**
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
}
I've come up with the following rudimentary solution, which is working so far, but I was wondering if there was a cleaner solution that follows Ember convention and best practices.
DS.ActiveModelAdapter.reopen
namespace: 'api/v1'
App.Store = DS.Store.extend
adapter: '-active-model'
App.ApplicationSerializer = DS.ActiveModelSerializer.extend
serializeHasMany: (record, json, relationship) ->
if relationship.options.async
key = relationship.key
data = record.get("data.#{key}")
if data?
json[@keyForRelationship(key, "hasMany")] = data.mapBy(Ember.get(this, "primaryKey"))
return
In my understanding, the reason that the active model serializer skips has many relations is that it expects the backend to handle it. In a relational database, the values of a has many are not explicitly saved on the parent record. It is sufficient to save the foreign key in the child. When you ask for a cleaner solution - perhaps ActiveModelSerializer
is not the best fit for your API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With