createRecord that has hasMany relationship


#1
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


Pushing has many records into a new model
#2

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


#3

but the server know nothing about the relationship.


#4

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?


#5

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

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


#6

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