V
V
vovastradamus2015-04-21 19:15:25
Ember.js
vovastradamus, 2015-04-21 19:15:25

Adding an entry to hasMany() in emberjs. How to do?

Good afternoon.
I can't figure out how to push json to a specific object. I'm making a blog with categories, where the categories have a hasMany() field.
0MEix.png
In this picture I wrote manually and it works.
and here is my attempt to push:

var newPost = this.store.createRecord('post', {
  title: this.get('title'),
  body: this.get('body'),
  url_pic: this.get('url_pic'),
  publish: new Date().getTime()
});
var catId = this.get('category');
var postId = newPost.id;
newPost.save();

var addtocat = this.store.push('category', catId.posts, {
    postId : true
});
addtocat.save();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Romanov, 2015-04-21
@Kaer_Morchen

If you want to add a new post to a category after it has been created, do this:

var newPost = this.store.createRecord('post', {
  title: this.get('title'),
  body: this.get('body'),
  url_pic: this.get('url_pic'),
  publish: new Date().getTime()
});

var _this = this;

newPost.save().then(function(newPost) {
  _this.get('category.posts').pushObject(newPost);
}, function() {
  newPost.rollback();
});

If not, then explain what you want to do, it's hard to understand from the code and the picture.

V
vovastradamus, 2015-04-25
@vovastradamus

Stanislav Romanov , sorry for the late reply, but your answer didn't help. Writes "Cannot read property 'pushObject' of undefined". That is, as far as I understand, he does not understand what to add. Here is a little more detailed information:
Post model:

export default DS.Model.extend({
  title: DS.attr('string'),
  body: DS.attr('string'),
  autor: DS.attr('string'),
  publish: DS.attr('date'),
  url_pic: DS.attr('string')
});

Category model:
export default DS.Model.extend({
  name: DS.attr('string'),
  path: DS.attr('string'),
  posts: DS.hasMany('posts', { async: true })
  	//posts: DS.hasMany('post')
});

Here is the addition itself:
export default Ember.Controller.extend({
  actions: {
    publishPost: function() {
      var newPost = this.store.createRecord('post', {
        title: this.get('title'),
        body: this.get('body'),
        url_pic: this.get('url_pic'),
        publish: new Date()
      });

      newPost.save().then(
        function(newPost) {
        _this.get('category.posts').pushObject(newPost);
      }, function() {
        newPost.rollback();
      });
    }
  }
});

I tried to output this part to the console with _this.get('category.posts'), it simply displays the Id of the category where I add, i.e. he apparently does not see the model.
Are there any other suggestions? Thanks in advance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question