Dejan Biljecki
Dejan Biljecki

Reputation: 605

Adding objects to hasMany error

My form has body and subject inputs, and an input for tags, so the user can enter any number of tags (saved to tagList) and then submit the request. Problem: JSON.stringify(z) does something like this

New request:{"subject":"this is subject","body":"this is body","tags":["fixture-0","fixture-1"]}

instead of getting the tags to be the text I entered, I get fixture-0...

import Ember from "ember";
export default Ember.ArrayController.extend({

    tagList: [],

    actions: {
        addRequest: function() {

            var z = this.store.createRecord("Request", {body: this.get("body"), subject: this.get("subject")    
            });

            this.get("tagList").forEach(function(entry){
               console.log("adding tag to request: "+entry.get("tagt"));
                z.get("tags").pushObject(entry);
            });

            console.log("New request:" + JSON.stringify(z));

            z.save();

        },

        addTag: function(){

            console.log("adding " + this.get("tag"))
            var t = this.store.createRecord("tag", {tagt: this.get("tag")});
            this.get("tagList").pushObject(t)

        }

    }

});

Upvotes: 0

Views: 25

Answers (1)

GJK
GJK

Reputation: 37369

First of all, I don't think you can rely on JSON.stringify to convert your records to JSON properly, that's generally the job of a serializer. (Although I guess the toJSON method on the object could defer to the serializer, but I don't think it does.)

Second, this is expected behavior for Ember-Data. The names of the text aren't in the JSON because they don't need to be. You have a hasMany relationship, which means that the record only keeps references (IDs) to tag objects. Keeping the actual text in the object would be duplicating that information.

As a side note, judging by the fact that you're using Request as a model type name, I can say with a pretty good degree of certainty that you're using Ember-Data incorrectly. This may be part of the reason you aren't expecting Ember-Data to behave the way it is. I would suggest reading Ember's guide on models to better understand what Ember-Data is for, and why it's probably not a good fit for your use case.

Upvotes: 1

Related Questions