createRecord that has hasMany relationship

App.Product = DS.Model.extend({
    tags: DS.hasMany('tag'),
});
App.Tag = DS.Model.extend({
    name: DS.attr('string'),
    product: DS.belongsTo('product')
});

In controller

tags: Ember.A()

actions: {
    createTag: function () {
       this.get('tags').pushObject(this.store.createRecord('tag', {name: "a"}).save())
    },

    createProduct: function () {
        this.store.createRecord('product', {tags: this.get('tags')});
    }

}

Then, I got this

Cannot set read-only property "tags" on object

I believe you need to create the Product record first, and then pushObject the Tag references into it.

Something like this:

var greatProduct = this.store.createRecord("product", {productName: "Great Product"});

var newTag = this.store.createRecord("tag", {name: "a"});
newTag.save();

greatProduct.get("tags").pushObject(newTag);
greatProduct.save();

Am I understanding the issue correctly?

EDIT: Fixed the order of save calls

but the server know nothing about the relationship.

Sorry, I goofed the order of the save calls- I edited the example.

Are you saying that you don’t store the tags independently of the products on the server? If that’s the case, I don’t know that modeling it that way in ember data is the right approach. You may be able to do it if you customize the adapter to not send tags out to the server on tag.save(), but include the full tag objects in the request for product.save(). Anyone else have any insight into this?

thanks for your reply, it’s the order problem.

Another question, how to set two model’s many to many relationship?

Hi,

How did you solve this problem? (I currently have the same one…)

Do you have to first create the parent and then edit it to be able to add child relationship model? Or did you find a way to add your child relationship to the being created parent?

Thanks for your help!

Michael