In Ember Data, you cannot have the same entry duplicated in hasMany relationships

Describing a particular model:

#order/model.coffee
Order = DS.Model.extend {
  line_items: DS.hasMany 'product', {async: true}
}

When attempting to add products to the order, it was discovered that adding the same product multiple times does not work as expected:

#product/route.coffee
...
actions:
    # Example code illustrating the issue
    addToCart: (product1, product2)->
      order = @modelFor 'order'
      console.log order.get('line_items.length') # prints 0

      order.get('line_items').pushObject product1
      console.log order.get('line_items.length') # prints 1

      order.get('line_items').pushObject product2
      console.log order.get('line_items.length') # prints 2

      order.get('line_items').pushObject product1
      console.log order.get('line_items.length') # prints 2

      order.get('line_items').pushObject product2
      console.log order.get('line_items.length') # prints 2


      ...

The challenge arises when users need to include multiple instances of the same item in an order. Unfortunately, Ember does not seem to allow duplicate entries in relationships. How can models be added more than once to a relationship?

Answer №1

It appears that a line_items model with a quantity field is the appropriate solution instead of continuously adding the same item to your orders model without normalization.

I suggest implementing the following structure:

lineItem = DS.Model.extend({
    orders: DS.belongsTo('orders'),
    product: DS.belongsTo('products'),
    quantity: DS.attr('number'),
});

orders = DS.Model.extend({
    lineItems: DS.hasMany('lineItem', {async: true}),
    customerId: DS.belongsTo('customers'),
});

products = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    cost: DS.attr('string'),
});

This setup allows for the creation of multiple unique records in the lineItem model, each tied to a specific order. For example:

{
    "lineItem" : 
        [
            {
                "id": 1,
                "orderId": 1,
                "product": 1,
                "quantity": 100,
            },
            {
                "id": 2,
                "orderId": 1,
                "product": 2,
                "quantity": 10,
            },
            {
                "id": 3,
                "orderId": 2,
                "product": 1,
                "quantity": 100,
            }
        ]
}

In this design, you can omit the reference to lineItems in your JSON as ember-data handles the inverse relationship automatically. This approach ensures that altering a line item only impacts one order and changing the order associated with a lineItem is done directly on the lineItem model.

{
    "Orders" : 
        [
            {
                "id": 1,
                "customerId": 123456,
            },
            {
                "id": 2,
                "customerId": 123456,
            }
        ]
}

Answer №2

To ensure distinct items of the same product type can co-exist in the array, each item should have a unique id property separate from other properties.

Alternatively, one record can represent a product type with a quantity attribute to indicate the quantity of each product available.

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

Activate mouseover function automatically for each feature on the leaflet

I'm facing a challenging situation where I need to develop a dashboard application that is similar to the functionality of ChoroplethExample. However, the catch is that I have to loop through all states (Features in geoJSON) and pause for 3 seconds at ...

The preflight response does not allow the access-control-request-methods request header field due to restrictions set in the access-control-allow-

I'm facing CORS issues while trying to make a POST request from my website to a remote server. Despite searching online, I couldn't find a solution that fits my specific problem. Below are the parameters for my ajax request: var params = { ...

Hover over the text only, not the entire row

Is there a way to create a mouse hover effect on text only, without affecting the entire row? I attempted using Position(), but didn't have success. Here is a link to the fiddle I created: <ul id='ulid'> <li>Task1</li> < ...

How can Vuetify be used to create a v-row that floats above other elements, maintains a fixed position, and still adheres to the width of its parent element

Currently, I am integrating Vuetify into my project and facing an issue with making an element inside a v-row float and fixed while still maintaining the width of the parent element. Here's the code snippet I am working with: <v-container> ...

What is the method to have text added automatically to an input field when a key is pressed?

Within my navigation, I have implemented a "full-screen overlay search box". When users click on the magnifying glass icon, a full-screen overlay with a search input field appears. You can see an example image here: . Currently, to enter text in this full ...

Is there a way to switch a class on a specific element inside a bulleted list when the parent div is clicked?

I'm facing a simple issue that I can't seem to resolve. My goal is to toggle a class within an unordered list. Specifically, when the 'profile' div is clicked, I want to locate the next instance of 'profile-text' and add the & ...

Restricting the amount of visible

I have a Q&A section with multiple stacked boxes. I noticed that opening all the boxes made the page too long, so I'm exploring if JavaScript or jQuery can help limit the number of active boxes. $(document).ready(function() { $(".faqOuter").c ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Utilizing jQuery for validating latitude and longitude coordinates with regular expressions

I implemented jQuery validation in the following way: $("#register-form").validate({ rules: { latitude: { required: true, strongCoord: true }, longitude: { required: true, strongCoord: true } }, messages: { yrAr: { required: &a ...

Adaptable filler text

I am looking for a placeholder that can hold changing values: <input type="text" placeholder="Search by Name, Order Number and Location" style="width: 300px" /> <input type="text" placeholder="Search by Name" style="width: 300px" /> My goal ...

Client sites are not displaying any data through sockets

My goal is to transmit data using socket.io from my nodejs server to the client. The data I am receiving originates from pusher. I have an express backend and set up my server like this: #!/usr/bin/env node var debug = require('debug')('t ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

Npm publish seems to be stuck without generating any output

I'm having trouble trying to publish a package that I created. The files can be found at this Github Repo. When I run the command npm publish, it just seems to hang without any errors or output. I've attempted logging in using npm login and npm a ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

Tips for accessing JSON data stored as keys within a JavaScript object

I'm facing an issue with my Node.js lambda function that involves parsing JSON data received from an external application. The JSON data seems to be malformed and arrives as an object key, shown below: console.log(req.body) This results in: { &apo ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...