Let me use Posts and Comments to describe my problem. Inside my post_controller I wish to create a new record for a comment for that current post. What is the ember way to do this?
The relation is set like this:
App.Post = DS.Model.extend({
comments: hasMany('comment'),
});
App.Comment = DS.Model.extend({
post: belongsTo('post')
});
Inside my post_controller I want to create a record. I have this inside an action that is triggered from a template:
App.PostController = Ember.ObjectController.extend({
...
actions: {
createComment: function() {
var post = this.get('model'); // Edit: Forgot that I had this declared outside createRecord
var comment = this.store.createRecord('comment', {
content : "content",
post : post // This is where the problem is
});
}
}
});
However, I get an error saying: Uncaught TypeError: Cannot read property 'post' of undefined
How do I declare this relationship? Thanks.
Edit: The ember-data error comes from this internal function in ember-data.js:
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'), belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key]; // ERROR OCCURS HERE!
if (isNone(belongsTo)) { return null; }
store.fetchRecord(belongsTo);
return belongsTo;
}).property('data').meta(meta);
};
EDIT: Problem solved!
The problem was that I hade given comment an attribute called data. That attribute was in conflict with internal ember. Removing it made my code above work fine.