Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - How to make embedded hasMany relationships work with ember data

I can't get embedded hasMany to work correctly with ember data.

I have something like this

App.Post = DS.Model.extend({
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.extend({
  post: DS.hasMany('App.Post'),
  name: attr('string')
});

And my API returns the following for GET /post:

[
  {
   id: 1
   comments: [{name: 'test'}, {name: 'test2'}]
  },
  ...
]

I need to send this with POST /post:

[
  {
    comments: [{name: 'test'}, {name: 'test2'}]
  },
  ...
]

I want to work with Ember models and have them make the appropriate requests:

var post = App.store.createRecord(App.Post, hash_post_without_comments);
post.get('comments').createRecord(hash_comment);

App.store.commit(); // This should call the POST api 

and

var posts = App.store.find(App.Post); // This should call the GET api 

When I try something like post: DS.hasMany('App.Post', {embedded: true}), the GET is working but the POST is trying to make a POST for the two records not only the parent one.

EDIT : My Real use case

1- I've just built ember data from master

2- My adapter: RESTAdapter

3- The serializer: JSONSerializer

4- I added

App.MyAdapter.map('App.Join', {
    columns: { embedded: 'always' }
});

5- My Models are:

App.Join = DS.Model.extend({
    rowCount: DS.attr('number'),
    columns: DS.hasMany('App.JoinColumn'),
});

App.JoinColumn = DS.Model.extend({
    join: DS.belongsTo('App.Join')
});

6- When:

var a = App.Join.find(1);
a.get('columns').createRecord({});
App.store.commit();

a POST for joincolumn is sent and the parent is not dirty

What am i missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On master, the correct API is:

App.Adapter.map('App.Post', {
  comments: { embedded: 'always' }
});

The two possible values of embedded are:

  • load: The child records are embedded when loading, but should be saved as standalone records. In order for this to work, the child records must have an ID.
  • always: The child records are embedded when loading, and are saved embedded in the same record. This, of course, affects the dirtiness of the records (if the child record changes, the adapter will mark the parent record as dirty).

If you don't have a custom adapter, you can call map directly on DS.RESTAdapter:

DS.RESTAdapter.map('App.Post', {
  comments: { embedded: 'always' }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...