ember.jsember-dataactive-model-serializers

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.


Solution

  • 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 this instead of the above.

    App.ActivitySerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
      attrs:
        user: {embedded: 'always'}
        category: {embedded: 'always'}
    
    
    App.ApplicationAdapter = DS.ActiveModelAdapter.extend
      defaultSerializer: 'DS/app'