Multiple serializers for a single model

﹥>﹥吖頭↗ 提交于 2019-12-11 13:36:35

问题


I have a User model that hasMany Reminders.

When a User is first created, I want the reminders to be embedded. When it is updated, I don't want its reminders to be embedded. How can I do this?

My strategy was to create a custom new-user-serializer that had DS.EmbeddedRecordsMixin and

reminders: { embedded: 'always' }

and use that in my UserAdapters createRecord method, but I couldn't get it working.


回答1:


It's not ideal, but you can do it -

`import DS from 'ember-data'`
`import ApplicationSerializer from './application'`

UserSerializer = ApplicationSerializer.extend DS.EmbeddedRecordsMixin,

    attrs:
        reminders: {}

    serialize: (snapshot, options) ->
        if snapshot.attr('embedRemindersFlag')
            @attrs.reminders.embedded = 'always'
        @_super(snapshot, options)

`export default UserSerializer`

embedRemindersFlag has to be an attribute of the model so snapshot picks it up, but I have separately implemented a transient option which prevents an attribute from being sent to the server.

embedRemindersFlag: DS.attr 'string', {defaultValue: false, transient: true}


来源:https://stackoverflow.com/questions/27710419/multiple-serializers-for-a-single-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!