EmberJS: Learning how to create a record with a belongsTo relationship

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.

Answer №1

If you define your post before the createRecord function (specifically above the declaration of var comment)

assigning postModel = this.get('model');

You may encounter a problem with referencing "this" within the createRecord context

Update

Furthermore, have you tested if accessing this.get('model') and this.get('content') returns the same output outside of that specific scope?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem. "A task for you: Calculate the average score of a class whose test scores have been graded by a teacher. Your mission is to complete the getAverage function, which receives an array of test sco ...

Exploring the possibilities: Utilizing HTML5, File API, and jQuery to

I have a form displayed in a dialog and it includes a "submit" button which, when clicked, utilizes jQuery to send the form data to the server via AJAX. However, I encountered an issue where the uploaded file was always null. After researching on Google, I ...

Having trouble with using findByIdAndUpdate and push in MongoDB?

As someone who is new to Mongodb, I have been using the findByIdAndUpdate function to update a document in my project. However, I noticed that it returns the old document instead of the updated one. Below is the code snippet of my function: exports.crea ...

Adjust the color according to the key's value in every object within the array

Issue: I am faced with an array of objects, each containing a Name key. At times, the names may be repeated. I want to maintain the same color when the name is the same and switch to a different color when the name changes. Specifically, I want to alternat ...

How can we stop the Replace function from replacing spaces as well?

When I trigger a paste event in an input field, I have a method that replaces all special characters. However, it is also removing empty spaces between words. How can I prevent this from happening? checkSpecialCharacters(){ let value = this.form.get(&q ...

Exploring the Depths of NodeJS X-Ray Web-Scraper: Uncovering Hidden Gems within Sub Pages

Currently, I am attempting to scrape content using the node.js x-ray scraping framework. While I have successfully retrieved data from a single page, I am struggling with navigating through links and extracting content from subpages simultaneously. Althou ...

Curious about the method of refining a list based on another list?

As a beginner in coding, I am facing a challenge in my code.org assignment. I need to filter songs by a specific artist from a dataset. Currently, I have code that randomly selects an artist, but I am struggling to filter out songs by that artist from the ...

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

Switching between pages and updating the URL without needing to refresh the page, while still maintaining the content even after a refresh

After experimenting with jQuery's load() method to dynamically change content without refreshing the page, I encountered a recurring issue: the URL remains unchanged. Even when attempting to use history.pushState() to modify the URL, the problem pers ...

Retrieve HTML content from Vuetify components without displaying it on the webpage

I have a project where I need to retrieve the HTML code from various Vuetify components. Instead of just as a HTML string, I actually need it as a DOM element that can be easily added to the body. This is necessary for me to be able to utilize these compon ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

Obtaining an Array through a direct input on the command line

I am having trouble incorporating raw command line arguments in my Node.js application. When I try with simple variables, everything works as expected (node example.js variable) However, when I pass an array as an argument, it does not work properly (n ...

Is there a way to retrieve a raw value from the API response that matches the one shown in POSTMAN, but my attempts have been unsuccessful?

Looking for some assistance with fetching data from a front-end (React) to the raw value in JSON. Specifically, I'm having trouble with the login functionality. When I input my email and password, the response should match what I see in POSTMAN, but i ...

Is there a way to include the request body (req.body) in the msg object using express-winston?

My current challenge involves logging {{ req.body }} using the msg: object in express-winston. Even after whitelisting the body with expressWinston.requestWhitelist.push('body');, it still does not appear in the log. export const accessLogger = ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

The capability to scroll within a stationary container

Whenever you click a button, a div slides out from the left by 100%. This div contains the menu for my website. The problem I'm encountering is that on smaller browser sizes, some of the links are hidden because they get covered up. The #slidingMenu ...

Which directives in AngularJS facilitate one-way binding?

Which directives in AngularJS support one-way binding? While ng-model enables two-way binding, what about ng-bind and {{ }} expressions - do they also support one-way binding? ...

Using jQuery and AJAX to dynamically add data to POST parameters

Hello, I have a question that may sound like one from a newbie. I am trying to figure out how to insert a variable into a parameter for a POST request instead of simply writing the number in directly: var x = 3; id=(the var x needs to be here)&appid=4 ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...