Search code examples
ember.jsember-dataember-cli

How can I serialize hasMany relations with ember-data > beta15?


Until ember-beta 14, everything was going fine. I have goal and account models.

goal hasMany('account'), but account does not have or belongs to goals (not on ember, there are no reason on my app.

With a custom serializer, I had all working fine:

//serializers/goal.js

    import DS from 'ember-data';

    export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
      attrs: {
        account: { serialize: 'ids' }
      }
    });

my post request had all I need:

...
  account_ids: [1, 2, 3]
...

now I just have account_ids: []. Ember nows about my serializer, otherwise I would just have accounts, not account_ids on the request.

I tried all possible combinations from docs, with and without {async: true}, etc, nothing works.

What am I'm doing wrong?

I feel that it has something to do with the new snapshots api, but couldn't find any clue about how to work with it.

Thanks!


Solution

  • I had the same problem, but finally works with this:

    Models/foo.js:

    var foo = DS.Model.extend({
    ...,
    ...,
    ...,
    bars: DS.hasMany('bar', {async: true})
    });
    export default foo;
    

    Models/bar.js:

    var bar = DS.Model.extend({
    ...,
    Foos: DS.hasMany('foo', {async: true})
    });
    
    export default bar;
    

    Serializer/foo.js:

    import DS from 'ember-data';
    export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin,{
      attrs: {  
        Bars: {
         embedded: 'always'
        }
      }
    });
    

    Serializer/bar.js:

    import DS from 'ember-data';
    export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin,{
      attrs: {    
        Foos: {
              embedded: 'always'
            }
       }
    });
    

    I hope this help you.