When you create an object with associations in SailsJS, it automatically triggers an update

Currently, I am utilizing Sails version 0.10.5 for my project. In the development process, I have established three models interconnected through associations. These models include a Candidate, an Evaluator, and a Rating; where an evaluator provides ratings for a candidate. The Waterline associations are being used to automatically manage the foreign keys from the Rating model to both Evaluator and Candidate.

Moreover, I have implemented Blueprint to handle all CRUD routing operations seamlessly for these models.

However, a dilemma arises when creating a new candidate via Blueprint with a URL like

http://localhost:1337/rating/create?rating=4&comment=Great&evaluator=3&candidate=2
. This results in triggering not only the expected CREATE action but also initiating two UPDATE actions. Subsequently, during these UPDATE requests, the foreign keys linking to each of the Candidate and Evaluator models are set, leading to unexpected behavior on the front-end of my application which struggles to interpret the data due to receiving an UPDATE event instead of the anticipated CREATE event.

If anyone has any recommendations or solutions to circumvent this complication, your assistance would be greatly appreciated!

Below are the details of the Waterline models employed:

/api/models/Candidate.js:

module.exports = {
  schema: true,
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    status: {
      type: 'string',
      required: true
    },
    role: {
      type: 'string',
      required: true
    },
    ratings: {
      collection: 'rating',
      via: 'candidate'
    }
  }
};

/api/models/Evaluator.js:

module.exports = {
  schema: true,
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    title: {
      type: 'string',
      required: true
    },
    role: {
      type: 'string',
      required: true
    },
    ratings: {
      collection: 'rating',
      via: 'evaluator'
    }
  }
};

/api/models/Rating.js:

module.exports = {
  schema: true,
  attributes: {
    rating: {
      type: 'integer',
      required: true
    },
    comment: {
      type: 'string',
      required: false
    },
    evaluator: {
      model: 'evaluator',
      required: true
    },
    candidate: {
      model: 'candidate',
      required: true
    }
  }
};

Answer №1

Dealing with a comparable issue, I came up with a solution. By implementing a filter within the update event function, you can easily monitor changes in specific variables. If these variables have been updated, you can trigger a function that will make necessary adjustments to your front-end interface.

Answer №2

To customize the publishCreate function for the Rating model, you can create a simple method in your models/Rating.js file. The default publishCreate method is primarily focused on determining which associations to notify about the new model and how to notify them. Since this may not be what you want, you can simplify the method as follows:

publishCreate: function (values, req) {

  // Fetch all "watchers" of the Rating model
  var watchers = Rating.watchers();

  // Exclude the socket responsible for the creation if you don't want it to receive the "create" message
  watchers = _.without(watchers, req.socket);

  // Send a message to the sockets with the "rating" event and the expected payload for the "publishCreate" message
  sails.socket.emit(sockets, "rating", {
      verb: 'created',
      data: values,
      id: values[this.primaryKey]
  });

  // Subscribe all watchers to the new instance, if desired
  this.introduce(values[this.primaryKey]);

}

Keep in mind that publishCreate is a static method of the model, so it should be placed outside the attributes object.

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

Utilizing node.js and sockets in my backbone application: a comprehensive guide

I have a question that I believe is fairly simple to answer. My node.js server is installed at /usr/local/bin/node The index.html and server.js files are located at /usr/local/bin When I run node, everything works fine. I have a chat application runni ...

Transitioning from the login screen to the main page in Ionic with the help of Angular

My code is running smoothly, but I encountered an issue when clicking the login button. It changes the state as depicted in the image, altering the URL but failing to open the subsequent page. Can anyone provide guidance on how to redirect to the next page ...

Tips for maintaining the latest HTML, CSS, and JS files in Angular2/4 frontend hosted on IIS

When it comes to IIS, there are various settings that can affect the freshness of files. One setting involves Output Caching, where you can create cache rules such as enabling Kernel-mode caching and utilizing file change notifications. Another sett ...

How to align the horizontal title of the yAxis in HighCharts

I have two charts with different yAxis titles. I am trying to align the titles horizontally to the right side of the chart (on the left side of the Y line). However, the alignment only seems to work vertically centered. I actually need the titles to be in ...

Display two separate views or templates on the screen using AngularJS

Currently, I am developing a mobile app powered by Angular and I am looking to create a unique view that displays halves of two separate views. The user should be able to switch between the two views by swiping up or down. Can anyone provide advice on how ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

AngularJs' dir-paginate feature generates a distinct row number for each table row it creates

Is there a way to assign row numbers to each table row generated by dir-paginate in AngularJS? I've tried two methods but encountered errors with both. First approach : <tr dir-paginate='customer in Customers| itemsPerPage: 10'> ...

What could be causing only two out of my three Highcharts Pie Charts/Graphs to appear on the screen?

I'm facing an issue where my charts display perfectly when uploaded to JFiddle, but on my actual webpage only 2 out of 3 charts appear. Could I be overlooking something? All my JavaScript code is properly formatted and tags are closed. This problem h ...

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

Having trouble retrieving alert message after submitting form using jquery

Trying to submit a form using jQuery, but when clicking on the submit button it displays a blank page. I understand that a blank page typically means the form has been submitted, but I want to show an alert() for testing purposes instead. However, it only ...

PHP is encountering issues when attempting to dynamically add rows using JavaScript

I have created this HTML code to dynamically generate rows: <tr > <td><?php echo $row['qty'];?></td> <td class="record"><?php echo $row['prod_name'];?></td> <td><input type ...

Reorganizing Rows with JQuery DataTables

I've been working on a function to swap rows in a table, but for some reason, it's not functioning as expected. The data within the rows doesn't align properly with the array information. I could really use some help identifying any errors i ...

Begin using datatables with the xp:table component

Within an XPage, there is a table component: <xp:table id="tblProposals"> I am looking to apply the datatables plugin to this table using a scriptblock component: <xp:scriptBlock id="scriptInitProposals"> < ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

Navigating within an ng-if or ng-show in AngularJS

Currently, I am developing a web application using AngularJS and there are times when I need to verify if the element inside the ng-if or ng-show directive belongs to a specific list. The approach I am using right now is shown below: <div ng-if="object ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

The numerical value fluctuates upon utilizing JSON.parse( )

I am currently utilizing Node/Express to send API requests to the unofficial Vine API. The data returned by the GET https://api.vineapp.com/users/search/ route undergoes changes during parsing. This is my code snippet: request({ url: 'https://api.v ...

Update the scatter/line chart dynamically in Chart.JS by incorporating multiple x and y grids for enhanced visualization

I need to develop a new function that will allow me to input data to update my line chart. Here is the current state of my function: function updateChart(label, xp1, yp1, xp2, yp2) { chart.data.labels.push(label); chart.data.datasets.data.push({x: xp1 ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...