Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.JS ActiveModelAdapter and Active Model Serializers default behavior

I have a simple active model serializer:

class ActivitySerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :time
  has_one :category
  has_one :user
end

I have category and user serializers as well, and they work as expected. I get this payload:

{"activities":[{"id":1,"title":"Test Activity","description":null,"time":"2014-03-01T06:05:41.027Z","category":{"id":1,"title":"Sports"},"user":{"id":1,"name":"ember"}}]}

However they don't seem to load into ember.

App.Activity = DS.Model.extend
  title: DS.attr('string')
  description: DS.attr('string')
  time: DS.attr('date')
  category: DS.belongsTo('category')
  user: DS.belongsTo('user')

App.Category = DS.Model.extend
  title: DS.attr('string')
  activities: DS.hasMany('activity')

App.User = DS.Model.extend
  name: DS.attr('string')
  activities: DS.hasMany('activity')

When I check the ember inspector the data isn't loaded. What kind of format is ActiveModelSerializer expecting? It loads an activity but not the category or user attributes.

like image 737
Ryan Taylor Avatar asked Feb 25 '14 01:02

Ryan Taylor


2 Answers

The trick took me a bit to find online, my model needed to include embed :ids.

class ActivitySerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :title, :description, :time
  has_one :category
  has_one :user
end

Alternatively, you can do something along the lines of, but no promises I never tested this code.

App.ActivitySerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
  attrs:
    user: {embedded: 'always'}
    category: {embedded: 'always'}


App.ApplicationAdapter = DS.ActiveModelAdapter.extend
  defaultSerializer: 'DS/app'
like image 176
Ryan Taylor Avatar answered Oct 22 '22 02:10

Ryan Taylor


The embed id's as mentioned by Ryan works, but you might have problems with inflections such as organized_by becomes organized_bies and then you have to configure both sides to correct it. The JS code required to fix this problem is:

DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: { category: {embedded: 'always'} }
});
like image 39
Pierre Pretorius Avatar answered Oct 22 '22 03:10

Pierre Pretorius