Emberjs Troubleshooting: Issue with Sending Many-To-Many JSON Parameters

My current versions are ember-cli 1.13.8 and ember-data 1.13.11, using ActiveModelAdapter.

I am working with two objects: posts and users. On an individual post page, I have implemented an action that allows users to watch/follow the post.

//post model js
watchedUsers: DS.hasMany('user', { inverse: 'watchedPosts', async: true });

//user model js
watchedPosts: DS.hasMany('post', {inverse: 'watchedUsers', async: true });

//action after clicking button
action: {
    addToWatchlist(post) {
        //session.current user is declared in an initializer that lets us access the current user easily
        post.get('watchedUsers').pushObject(this.get('session.currentUser'));

        post.save().then(function() {
            console.log('post save success');
        }, function() {
            console.log('post save fail');
        }
    }
}   

After clicking the follow button in the ember inspector, I can see that the watchedUsers attribute for the post model updates, as well as the watchedPosts for the user model. However, these values disappear upon refreshing the page. It seems like the pushObject function is functioning correctly.

Upon inspecting the PUT request to my backend to save the post model, I noticed that it does not contain the json entry for the watched_user_ids. This indicates that it is not being saved properly, which I believe is the root of my issue.

Despite having seeded data in my rails backend that is accessible on the ember side, the many-to-many relationship does not seem to be supported by ember-data. I wonder if there are any specific steps or configurations needed to send/save the json for such a relationship?

Answer №1

I successfully tackled this issue by implementing a 'watchlist' object between Post and User to represent their many-to-many relationship. Instead of using has and belongs to many, I utilized a many-to-many :through approach on the backend with Rails. One challenge I faced was Ember Data's lack of sending json for HasMany attributes.

Below is how the final solution appeared:

//models/user.js
export default DS.Model.extend({
     watchlists: DS.hasMany('watchlist', { async: true })
});

//models/post.js
export default DS.Model.extend({
     watchlists: DS.hasMany('watchlist', { async: true })
});

//models/watchlists.js
export default DS.Model.extend({
    user: DS.belongsTo('user', { async: true }),
    listing: DS.belongsTo('listing', { async: true }),
});

//action in a route.js
actions: {
    addToWatchlist(post) { //component sends the specific post using sendAction
        var newWatchlist = this.store.createRecord('watchlist', {
            user: this.get('session.currentUser'), //current user stored in session object
            post: post
        });
        newWatchlist.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

Order of tabs, dialog, and forms customization using Jquery UI

I'm currently working on a jquery dialog that contains a form split into multiple tabs. In order to enhance keyboard navigation, I am looking for a way to make the tab key move from the last element of one tab to the first element of the next tab. Cur ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Trouble Arising in Showing the "X" Symbol upon Initial Click in Tic-Tac-Toe Match

Description: I'm currently developing a tic-tac-toe game, and I've run into an interesting issue. When I click on any box for the first time, the "X" symbol doesn't show up. However, it works fine after the initial click. Problem Details: ...

What is the process for creating a line using points in three.js?

Can anyone provide a solution for creating a straight line using new THREE.Points()? I attempted to place particles and set their positions with an array and for loop, but the spacing was inconsistent. ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

Tips for positioning a div next to an input box when it is in focus

I am working on a scenario where I have used CSS to extend the search box when focused. The idea is that when the search box is focused, it should decrease in size and a cancel button should appear next to it. This is the CSS code I am using: .clrble .fr ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Retrieving specific JSON data using jQuery GET method and specific values

Here is the code snippet I am working with: $.ajax({ url: 'api/api.php?getPosts&lat=' + latitude + '&long=' + longitude + '', type: "GET", dataType: "html", ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...

Error: "Access-Control-Allow-Origin" header is missing in Firebase Function

I have encountered an issue with my firebase functions GET request. While I am able to receive data using Postman, I am facing difficulties when trying to fetch data from my front-end application. Upon accessing the endpoints, I am seeing the following er ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Unable to retrieve the array from the JSON data

Hey there, I'm currently working on parsing JSON data ** { "message": "gradeExam.php", "id": "171", "student_id": "dfd", "questions": [{ "question_id": "0", "student_input": "def doubly_" }, { ...

Assign a specific index value from a PHP array to a JavaScript variable

Having a large PHP array with 649 indexes, I am looking to assign a specific index value to a JavaScript variable based on another variable. Is there a way to achieve this without loading the entire PHP array onto the client side for speed and security rea ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

jqgrid now features inline editing, which allows for the posting of only the data that

My jqGrid includes editable columns, and I am looking for a way to only post the data of columns where changes have been made. Here is an example of my colModel: colModel: [{ name: 'I_PK', index: 'u.I_PK ...

Updating state array within reducer leads to duplicate execution of calculations

const updateCartReducer = (state, action)=>{ console.log('running the updater function') const existingItemIndex = state.items.findIndex( (item) => item.restaurant === action.item.restaurant && ...

Merge identical year items into a single entity

I have an array of objects containing car data: [ { year: 2019, company: 'Toyota', quantity: '450' }, { year: 2019, company: 'Ford', quantity: '600' }, { year: 2020, company: ...

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

How can I effectively retrieve automatically generated data being posted to the URL I'm working on in my Django application?

I am currently working on a project where data is automatically sent via a POST request to the URL I am developing on in the form of a JSON string. What is the proper way for me to fetch this data in my function-based view so that I can manipulate it effe ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...