문제

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.

도움이 되었습니까?

해결책

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'

다른 팁

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'} }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top