My issue involves using Posts and Comments to explain my problem. In my post_controller, I am trying to create a new record for a comment related to the current post. What is the recommended way to achieve this in Ember?
The relationship between Post and Comment models is defined as follows:
App.Post = DS.Model.extend({
comments: hasMany('comment'),
});
App.Comment = DS.Model.extend({
post: belongsTo('post')
});
Within my post_controller, I want to create a new comment record. The code snippet below shows how I'm attempting this within an action 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 encounter an error message stating: Uncaught TypeError: Cannot read property 'post' of undefined
How should I define this relationship properly? Thank you.
Edit: The ember-data error arises from an 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: Issue Resolved!
The problem stemmed from naming an attribute in the comment model as 'data,' which clashed with Ember's internal workings. Once I renamed it, the code functioned correctly.