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

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

Make sure to use dispatch when updating the array to prevent any potential infinite loops

I am currently working with JSX to create a function that reads user profiles and updates them upon clicking a button. The object userProfiles contains existing user profile data, which should be updated by combining the current contents with those from ne ...

Python error: Index out of range when utilizing index() function

@bot.command() async def start(ctx): edit = [] with open("wallet.json", "w") as file: for obj in file: dict = json.load(obj) edit.append(dict) userid = [] for player in edit: user ...

Using npm as a build tool to merge files together

Upon discovering the flexibility of using npm as a task runner instead of gulp or grunt, I have successfully implemented various tasks such as linting, stylus processing, jade compilation, uglifying, and even watching files. However, I am facing difficulti ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

Use the JavaScript .replaceAll() method to replace the character """ with the characters """

My goal is to pass a JSON string from Javascript to a C# .exe as a command line argument using node.js child-process. The JSON I am working with looks like this: string jsonString = '{"name":"Tim"}' The challenge lies in preserving the double q ...

Executing a Javascript function using ssl

As a newcomer to SSL and Javascript, I hope you'll pardon any lack of knowledge on my part. I've been trying to research my question online, but haven't had much luck finding the answer. Context In simple terms, my website has a subdomain ...

Tips for sending data from an HTML page to an Angular custom element

I have successfully created an angular custom element from an angular component that I would like to call from a standard HTML page. The custom element requires a parameter, which functions properly when called as a component within an angular project. Ho ...

Enabling CORs headers in Express continues to lead to errors

I have implemented the CORS code provided on http://enable-cors.org/ for express into my index.js file. /*these first five line direct from http://enable-cors.org/.com*/ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); ...

Leverage the power of an Express server to manage a Node.js application

I have a node.js application that communicates with a REST API hosted on a separate server. To control this application, I want to create a web interface using express.js which includes HTML, CSS, and Javascript. How can I enable the browser to interact w ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

Protractor - Resolving as pending promise when executed

I have been working on creating a function that can search through an array of elements and return the first element that meets certain criteria. Here is my test code that works as expected: element.all(by.css('_cssSelector_')).filter(function( ...

Send a variety of jQuery element selectors to a function

myFunc() is connected to the document scroll event, resulting in frequent calls. To optimize performance, I intend to store HTML selections in variables and then pass them to the function. However, upon running the code snippet below, an error appears in t ...

Utilize the AWS resource aws_route53_record in Terraform to efficiently import route 53 records from a JSON file

Currently, I am exploring the process of importing DNS records from a JSON file. The interesting part is that there can be multiple JSON files in the same folder, each containing one or more DNS records like below: [ { "dnsName":"my ...

Distinguishing between native and custom error objects: a comprehensive guide

When working with errors in my node app, I find it challenging to handle both custom and native errors seamlessly. Errors are not just ordinary JavaScript objects, which adds complexity to error handling. To manage custom errors, I am experimenting with t ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

Tips for handling a lone value while incorporating custom handlers in jsonpickle

In order to customize the serialization process for an object containing enum values, I created a custom handler using jsonpickle. import jsonpickle from enum import Enum class Bar(Enum): A = 1 B = 2 class Foo: def __init__(self): ...

Unused function in Vue error compilation

I am facing an issue with the compiler indicating that the function 'show' is defined but never used. The function show is being used in HTML like this: <b-card> <div id="draw-image-test"> <canvas id="can ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

Blogger Extension - Cross Domain Communication

As I work on creating a blogger plugin, my goal is to send information from the blog page for analytic purposes and then display the results on the visitor's page. Initially, I tried sending the page content using an ajax call but encountered an error ...