What is the process for automatically saving associated models when saving the main model?

In my quiz manager, I am working on allowing users to add questions and edit the answers for those questions. My goal is to have a single save button that saves both the questions and their corresponding answers. However, when trying to access and call the save() method from the question save(), I encounter an error stating "There is no save method". Please let me know if you require more information.

Question Controller

App.QuestionController = Ember.ObjectController.extend({
        softSave: function() {
            var self = this;
            this.get('model').save().then(function() {      
                self.get('answers').save();
                console.log('%c Question was saved','color:green;');

            }, function() {
                console.log('%c Question not saved', 'color:red;');
            });
        }
    }

});

Question Model

App.Question = DS.Model.extend({
  'quiz': DS.belongsTo('quiz'),
  'text': attr('string'),
  'ord': attr('number'),
  'answers': DS.hasMany('answer' , { async: true } )
});

Answer Model

 App.Answer = DS.Model.extend({
  'question': DS.belongsTo('question'),
  'content': attr('string'),
  'correct_answer': attr('boolean')
});

Answer №1

It appears that the issue lies in the fact that answers is not simply a model; rather, it is an array of models. To resolve this, one potential solution is to implement the following:

App.QuestionController = Ember.ObjectController.extend({
  quickSave: function() {
    var self = this;
    this.get('model').save().then(function() {     
      self.get('answers').forEach(function(answer) { answer.save(); });
    });
  }
});

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

Encountering question marks while attempting to retrieve data from the API

I have developed an application using node-webkit that notifies me whenever there is an alarm in my country due to the ongoing war. There is a particular website that provides a JSON file containing information about current alerts. However, when I attem ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

The datepicker UI triggers the onChangeMonthYear event before executing the beforeShowDay function

I am currently using the jQuery Datepicker UI (http://jqueryui.com/datepicker/) My goal is to dynamically color specific days based on data retrieved from an AJAX call. This is the current setup: $(document).ready(function() { getAllDays(); $("# ...

Using JavaScript regular expressions to validate currency without relying on jQuery

Looking for a solution to create a money mask for an input field without using jquery in my application. Is it possible to achieve this using regular expressions with 'on key up' events, for example? Below is the code snippet: <tr> & ...

Can you explain the distinction between a synchronous and asynchronous request in terms of their async parameter values (true/false)?

Can you explain the difference between setting async=false and async=true when utilizing the open method of the XMLHttpRequest? function GetXML() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new X ...

Tips for showcasing overflowing text in a menu list by rotating the item text

Imagine you have a TextMenuItem component, using MenuItem from the Material-UI library, that is part of a chain consisting of DropDownSearch > SimpleListMenu > FixedSizeList > TextMenuItem. In simple terms, this creates a searchable dropdown eleme ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

An error was encountered: An identifier that was not expected was found within the AJAX call back function

I am experiencing an issue while attempting to query an API. An Uncaught SyntaxError: Unexpected identifier is being thrown on the success part of my JQuery Ajax function. $(document).ready(function(){ $('#submitYear').click(function(){ let year ...

Questioning the way spyOn "halts all execution of a function" is described in the Jasmine documentation (specifically in the section on Spies in version 2.2)

I am struggling to comprehend the last test in the Jasmine 2.2 documentation which showcases the basic usage of Spies. In the beforeEach() section, we initialize bar = null, then we spy on foo.setBar and proceed to call foo.setBar twice. I am puzzled as t ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

What is the best way to send data between pages in a React application?

After solving the question, I can confirm that the code lines are correct. By utilizing console log, I verified that all parameters are being passed correctly: I am creating a website to showcase my personal projects, using components across different pag ...

Create movement in line art using the position of the cursor

I have created a skull lineart in illustrator and I am trying to make the lines fill in or erase based on mouse position. There are two possible ways to achieve this: Using lazy line painter to draw the lines and then finding a way to animate based on ...

Tips for utilizing the key special attribute with the v-for directive when working with an array of arrays

List item There is a variable that contains an array of arrays of objects in the following format: let FooVar: Array<Array<FooObject>> = [] ; The task is to iterate through this variable inside a component using the following structure: <s ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

I encountered an error stating that ".then" is not defined during my attempt to save

Just starting out with node.js and I encountered an issue: TypeError: Cannot read property 'then' of undefined This is the code snippet causing the problem: router.post("/signup", (req, res) => { const userRegister = new UserRegister({ ...

Can someone guide me on how to personalize a marker icon in Quasar while utilizing Vue2-Leaflet for mapping?

I'm facing an issue with displaying an icon marker image in my Vue2-Leaflet and Quasar project. Instead of the desired image, I am seeing a broken image icon and encountering a 404 error in the console. Despite researching various solutions, I was abl ...

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

Utilizing PHP Variables in JavaScript: A Comprehensive Guide

Is there a way to work around the inability to directly use PHP variables in javascript code? I need to incorporate these parameters into my javascript: username: '<?php echo $user_id;?>.example.co.uk', password: 'example', Inst ...

Adjusting transparency of uploaded 3D model in Three.js

I've successfully loaded a 3D object model into a three.js scene using the following code: var skull; var loader2 = new THREE.ObjectLoader(); loader2.load( 'skull.json', function(object) { skull = object; scene.ad ...

Looking for a .NET MVC AJAX search solution. How can I enhance the code below?

I am looking to implement a search functionality using AJAX. I have tried using the get method in my controller by passing the search string, but it is not working as expected. Below is a snippet of my controller code, where I retrieve the search value fr ...