5
votes

I have the following model defined:

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  comments: DS.hasMany('comment')
});

App.Comment = DS.Model.extend({
  message: DS.attr('string')
});

If I create a Post entry with a Comment, the JSON stored in my browsers local storage references the Comments as an array of IDs which works great:

...
"o3duh":{
    "id":"o3duh",
    "title":"How to write Ember",
    "comments":[
        "jf0a2"
    ]
}
...

However, the moment I add another Post, the JSON suddenly changes such that Comments are embedded:

...
"o3duh":{
    "id":"o3duh",
    "title":"How to write Ember",
    "comments":[
        {
            "message":"First!"
        }
    ]
},
"6kudl":{
    "id":"6kudl",
    "title":"Learning Ember is painful",
    "comments":[
    ]
}
...

Why is this happening? Can I prevent it? This is causing me problems because once it changes into this embedded format, the data cannot be read by the LSAdapter when reloading the page.

Here is a JSBin so you can see it happen for yourself and see the full JSON etc. To reproduce the problem, just create a post and add a comment then you can refresh the page without problem. Then add another post and try to refresh the page.

I'm not sure if the problem is with ember-data or the localstorage adapter.

2

2 Answers

1
votes

I solved the problem by modifying the LocalStorageAdapter so that it only attempts to persist JSON in the expected format.

You can see the pull request I submitted to the original author here: https://github.com/rpflorence/ember-localstorage-adapter/pull/26

Hopefully it will either get folded into the LSAdapter project, or better still, someone will come up with a better solution ;)

0
votes

I was able to fix the JSON issue by defining the inverse relationship on Comment:

App.Comment = DS.Model.extend({
  message: DS.attr('string'),
  post: DS.belongsTo('post')
});

There are new issues now, but hopefully this will help.