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?