The issue of saving Rails input from an Angular2 front end has been causing some trouble

Currently, I am in the process of developing a front-end application using Angular 2 that retrieves data from a Rails 5 API. This specific application serves as a network inventory tool.

One particular feature of this app is an Asset-form in Angular2 which includes a multi-select input for the IP addresses associated with the asset.

However, I have encountered an issue where Rails is not accepting this data at the back-end.

Here is an example of the asset object:

{"name":"SERVER_A","serial":"XOR-354","location_id":1,"asset_type_id":1,"model_id":3,"ip_address_ids":[5304,5305]}

In order to better illustrate the problem, let's take a look at my asset.service.ts code snippet:

createAsset(asset: Asset){

let formData = new FormData();

for(var key in asset){
  if(key == "ip_address_ids") {
    for (var i = 0; i < asset[key].length; i++) {
        formData.append("asset["+key+"][]", JSON.stringify(asset[key][i]));
        console.log("asset["+key+"][]", JSON.stringify(asset[key][i]));
    }

  }
  if(key != "id") {
    formData.append("asset["+key+"]", asset[key]);
  }
}

let headers = new Headers();

let authToken = localStorage.getItem('auth_token');
headers.append('Authorization', authToken);  

return this.http.post(this.assetUrl, formData, { headers })
                .map((response: Response) => response.json());}

Upon submitting the data, I noticed the following message in the Rails server console:

Started POST "/assets" for ::1 at 2017-02-06 13:58:33 +0100 


Processing by AssetsController#create as HTML   


Parameters: {"asset"=>{"name"=>"SERVER_A", "description"=>"undefined",
"serial"=>"XOR-354", "asset_tag"=>"undefined",
"firmware"=>"undefined", "ssh"=>"undefined", "telnet"=>"undefined",
"http"=>"undefined", "location_id"=>"1", "asset_type_id"=>"1",
"model_id"=>"3", "prtg_id"=>"undefined", "ticket_id"=>"undefined",
"ip_address_ids"=>"5304,5305"}}   

Unpermitted parameter: ip_address_ids

Despite permitting the 'ip_address_ids' parameter, the issue persists:

def asset_params
  params.require(:asset).permit(:name, :description, :serial, :asset_tag, :firmware, :ssh, :telnet, :http, :location_id, :asset_type_id, :model_id, :prtg_id, :ticket_id, :ip_address_ids => [])
end

I find it interesting that while using the Advanced REST Client in Chrome, the submission is successful.

You can view an image of the REST Client here

The resulting data in the Rails server console looks like this:

Started POST "/assets" for ::1 at 2017-02-06 14:04:42 +0100

Processing by AssetsController#create as HTML

Parameters: {"asset"=>{"name"=>"Test", "asset_type_id"=>"2", "location_id"=>"33", "model_id"=>"4", "ip_address_ids"=>["5213", "5214"]}}

My assumption is that the discrepancy lies in how Angular sends the IDs as a string, whereas the REST Client sends the IDs as an Array of strings.

Does anyone have any suggestions on how to address this issue?

Answer №1

The parameter ip_address_ids seems to be passed as a string instead of an array. Have you considered using

formData = JSON.stringify({asset: asset})
for a simpler approach?

If your intention is to pass it as a string, simply use :ip_address_ids without => [].

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

Track Your Instagram Followers with the Power of jQuery, JSON, and PHP!

Thanks to the collaboration of our team and the expertise of Sahil Mittal, we were able to successfully retrieve Instagram Follower Count using a combination of jQuery, JSON, and PHP. We are excited to share our code with anyone who is interested in obtain ...

The pipe operator in Angular is failing to function as intended

I encountered an error while using the replace operator in Angular. Can someone help me identify the issue? Check out this link for more information ...

Output the ID of each completed task from the JSON file using a bash script

Here is an example of a Json file: { "tasks": [ { "id": "nightly_1652299200", "repo": "tx/tx5", "branch": "dev", "type": "HealthCheck", ...

How to Open a Work Item in TFS 2017 Using an Angular Application

I recently developed a TFS 2017 extension using Angular Framework. One of the features in this extension is a table that includes a column for Work Item ID. The desired functionality is that when a user clicks on the ID, it should open up the corresponding ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

Simple steps to transform the "inputs" syntax into the "@Input" property decorator

There's this code snippet that I need to modify: @Component({ selector: 'control-messages', inputs: ['controlName: control'], template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) Is the ...

How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this: <script> var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998'; //auto-generated var myValues = ...

Declare a new variable with a specific data type in TypeScript

I'm working on creating a variable in my component of a specific type, as shown below. myrequest.model.ts export class MyRequest { public endValue: string; public yearEnd: string; } When importing the above into my component, I do the follow ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

Converting markdown files to JSON format with the help of G

I am attempting to convert a README file to JSON using the "gulp-markdown-to-json" plugin. However, when I run gulp from the command line, I encounter an error 'TypeError: md2json.parse is not a function'. Here are my project dependencies: "dev ...

Guide to setting a default value for a select option in Angular 2+

I am having trouble setting a default option in my select box using the html selected property. I want the selected option to be assigned to StartingYear, but currently it's not working as expected. <select [(ngModel)]="StartingYear"> < ...

What is the best way to convert this JSON into Swift data structure?

I attempted to read the text_entries, but I am struggling because the object contains integers ranging from 0 and beyond. How can I accurately parse this? What am I overlooking? Upon running the code, I encounter an error indicating that the JSON decoder ...

The controller returned a null value

I've encountered a situation where I'm utilizing a service file to execute a stored procedure: function createCampaign($campaignName, $groupNumber){ $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHE ...

Execute a function when an RXJS Observable has completed its operation

Using the RXJS Observable has been smooth sailing so far, but I now find myself needing to not only react to observer.next() but also when observer.complete() is called. How can I capture the OnComplete event of an RXJS Observable? The documentation for ...

Is there a node.js equivalent to Turbolinks available?

One of my favorite features in Rails is Turbolinks, as it enhances the user experience by making pages appear to load faster. Is there any alternative or similar functionality for node.js? ...

The string variable in the parent app is resetting to empty after being populated by the service call

I am facing an issue with my app components where AppComponent acts as the parent and ConfigComponent as the child. In the constructor of AppComponent, a service call is made to set a variable but I encounter unexpected behavior when trying to access this ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...

Struggling with manipulating arrays in Angular 7

Alright, let me give you the gist: Here's the deal - I've got a dataset chilling in sessionStorage, looking something like this: [{ "id": "123:456", "streetAddress": "1020 15th St", "point": { "lati": 35.74633, "longi": ...

Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo ...