IT TIP

Ember js-다른 테이블을 업데이트 한 후 Hasmany 관계가 끊어짐

itqueen 2020. 11. 28. 13:24
반응형

Ember js-다른 테이블을 업데이트 한 후 Hasmany 관계가 끊어짐


Ember.js를 local-storage-adapter와 함께 사용하고 있습니다. 레코드를 업데이트하는 동안 이상한 문제가 있습니다.

hasMany 관계가있는 게시물 및 댓글 모델이 있습니다.

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

다음은 내 게시물 및 댓글 컨트롤러입니다.

App.PostsController = Ember.ArrayController.extend({
    newTitle: '',
    actions: {
        create: function() {
            var title = this.get('newTitle');
            var post = this.store.createRecord('post', {
                title: title
            });
            this.set('newTitle', '');
            post.save();
        }
    }
});
App.CommentsController = Ember.ArrayController.extend({
    needs: "post",
    post: Ember.computed.alias("controllers.post.model"),
    newMessage: '',
    actions: {
        create: function() {
            var message = this.get('newMessage');
            var comment = this.store.createRecord('comment', {
                message: message
            });
            var post = this.get('post');
            var comments = post.get('comments');
            if (comments.get('content') == null) comments.set('content', []);
            comments.pushObject(comment);
            comment.save();
            post.save();
        }
    }
});

레코드를 만드는 동안 hasMany 관계가 올바르게 업데이트되었습니다.

{
    "App.Post": {
        "records": {
            "0v66j": {
                "id": "0v66j",
                "title": "post1",
                "comments": ["p31al", "tgjtj"]
            }
        }
    },
    "App.Comment": {
        "records": {
            "p31al": {
                "id": "p31al",
                "message": "comment 1"
            },
            "tgjtj": {
                "id": "tgjtj",
                "message": "comment 2"
            }
        }
    }
}

게시물을 편집하는 동안 문제가 발생했습니다. 사후 레코드를 편집하면 관계가 사라집니다. 몇 가지 검색을 수행하고 다음 코드를 찾았습니다.

DS.JSONSerializer.reopen({
    serializeHasMany: function(record, json, relationship) {
        var key = relationship.key;
        var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
        //  alert(relationshipType);
        if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
            json[key] = Ember.get(record, key).mapBy('id');
            // TODO support for polymorphic manyToNone and manyToMany
            // relationships
        }
    }
});

이것은 트릭을했고 잘 작동했습니다. 하지만 이제 또 다른 문제가 있습니다. 다른 레코드를 편집하면 모든 ID 참조가 다음과 같이 전체 개체로 대체됩니다.

{"App.Post":{"records":{"0v66j":{"id":"0v66j","title":"post2","comments":[**{"message":"comment 1"},
{"message":"comment 2"}**]},"8nihs":{"id":"8nihs","title":"post3","comments":["b4v2b","dbki4"]}}},
"App.Comment":{"records":{"p31al":{"id":"p31al","message":"comment 1"},"tgjtj":{"id":"tgjtj","message":"comment 2"},
"b4v2b":{"id":"b4v2b","message":"comments3"},"dbki4":{"id":"dbki4",
"message":"comments4"}}}}

Comment refrences should be comments":["p31al","tgjtj"] like this. but the ids are replaced as "comments":[{"message":"comment 1"},{"message":"comment 2"}]


When using ApplicationSerializer which extends LSSerializer, it seems to work.

Maybe it got fixed since asked?


I've noticed a few things in my path with Ember... and especially Ember-Data.

One of them is when dealing with associations I've had to manually re-add in the associations saving and having to re-save, and use addObject to in-memory associations as you're using a bit here. :)

Note that this usually only happens when I'm updating more than one new object at once. For example, if your post is new, and your comment is also new.

I'm a little worried to see the following code in your codebase, because it shouldn't need to be there. You shouldn't ever have null or non-array objects in your associations. I'm not sure what hackery you did with the Adapter and why it was necessary, but I hope that wasn't the reason:

  if(comments.get('content') == null)
    comments.set('content', []);

Anyway, the following code is how I would probably write your create action. It might help. I hope it does.

create: function() {
  // get the post for association on the new comment
  var post = this.get('post');

  // get the message to store on the new comment
  var message = this.get('newMessage');

  var comment = this.store.createRecord('comment', {
    message : message,
    post : post
  });

  comment.save().then(function(savedComment) {
    post.get('comments').addObject(savedComment);
  });
}

Note that it's a lot simpler. Generally if you're doing tricky complicated things, something's amiss and it's time to go back to basics and add one thing at a time, testing thoroughly between additions. :)

Good luck!

참고URL : https://stackoverflow.com/questions/19604244/ember-js-hasmany-relationships-breaks-after-updating-other-tables

반응형